Consider this:
typedef void (*ExecFunc)( int val );
class Executor
{
void doStuff() { mFunc( mVal ); }
void setFunc( ExecFunc func ) { mFunc = func; }
int mVal;
ExecFunc mFunc;
};
void addOne( int val ) { val = val+1; } // this could be passed as an ExecFunc.
Very simple. Suppose now that I want to templatize this?
typedef void (*ExecFunc)( int val ); // what do I do with this?
template < typename X > class Executor
{
void doStuff() { mFunc( mVal ); }
void setFunc( ExecFunc<X> func ) { mFunc = func; }
X mVal;
ExecFunc<X> mFunc; // err... trouble..
};
template < typename X > addOne( X val ) { val += 1; }
So how to I create a templatized function pointer?
In C++11, you can use this:
template<class X>
using ExecFunc = void(*)(X);
defines ExecFunc<X>
.
In C++03, you have to use this instead:
template<class X>
struct ExecFunc {
typedef void(*type)(X);
};
and use typename ExecFunc<X>::type
within Executor
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With