如何使用模板参数对函数指针进行类型定义
How to typedef a function pointer with template arguments
考虑一下:
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.
很简单。假设现在我想将其模板化?
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; }
那么如何创建模板化函数指针?
在 C++11 中,你可以这样使用:
template<class X>
using ExecFunc = void(*)(X);
定义 ExecFunc<X>
.
在 C++03 中,您必须改用它:
template<class X>
struct ExecFunc {
typedef void(*type)(X);
};
并在 Executor
内使用 typename ExecFunc<X>::type
。
考虑一下:
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.
很简单。假设现在我想将其模板化?
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; }
那么如何创建模板化函数指针?
在 C++11 中,你可以这样使用:
template<class X>
using ExecFunc = void(*)(X);
定义 ExecFunc<X>
.
在 C++03 中,您必须改用它:
template<class X>
struct ExecFunc {
typedef void(*type)(X);
};
并在 Executor
内使用 typename ExecFunc<X>::type
。