4 ms·
Because they can take integral types, they can take function addresses. This is a really interesting article: http://www.codeproject.com/Articles/11015/The-Imp
by mindvirus 12y ago
Because they can take integral types, they can take function addresses. This is a really interesting article:
http://www.codeproject.com/Articles/11015/The-Impossibly-Fast-C-Delegates http://www.codeproject.com/Articles/11015/The-Impossibly-Fas...
By passing the address of the function to the template, the compiler knows which function is going to be called - the idea being that a smart compiler can now inline your delegates for you.
- tpush 12y agoAt least in my experience, compilers are pretty good at pointer chasing and inlining. For example, in my code a function calls another function through a function pointer that was previously set via an exposed function. Much indirection, right? Well, clang with LTO is able to see which function's address will be assigned, and even further can determine that it's the only function whose address gets assigned to the pointer, and thus can inline the whole function into the body of the other function; across compilation units, across pointer indirection. Everything without templates/inline code.
- ambrop7 12y agoThe clean approach is to wrap functions into classes: class Wrap { void call() {...} }; template <typename F> { ... F::call(); } And with some imagination one can write a macro to do this wrapping given an existing function, used like this: void my_func(); using MyFuncWrapped = WRAP_FUNC(my_func); // Now MyFuncWrapped::call() calls my_func. My implementation of the wrapper: https://github.com/ambrop72/aprinter/blob/master/aprinter/meta/WrapFunction.h https://github.com/ambrop72/aprinter/blob/master/aprinter/me... . But note it doesn't use std::forward since this code assumes no references being used.
- cbsmith 12y agoBut you don't get much by wrapping it in that class and making a functor out of it, unless you want to manage state. Either way, in C++, it is a slim line between the two. C++11 lambdas have this quality of "a type for every function" as well.