Here's a manual way to avoid creating a class C
template:
struct C { template <typename Func> void foo(Func fun) { _myFunc = static_cast <void*>(&fun); stub = call <Func>; } void someOtherThing() { stub(_myFunc); } private: void* _myFunc; void (*stub)(void*); template <typename F> static void call(void* f) { (*static_cast <F*>(f))(); } }; struct S { void operator()() { std::cout << "in S" << std::endl; } }; int main() { S s; C myClass; myClass.foo(s); myClass.someOtherThing(); }
When you call foo()
, the Func
type is "stored" inside the static function of the call
template, a pointer to (instatiation of), which is stored in stub
. The latter is called by someOtherThing
to actually call _myFunc
, which is nothing more than a simple void*
. To make this happen, _myFunc
first returns to the correct type, which is known only inside the call
body.
The only catch is that using function pointers there cannot be an insert to call stub(...)
.
iavr source share