开发者

Function pointer as a template

How to write a function pointer as template?

template <ty开发者_StackOverflow中文版pename T>
T (*PtrToFunction)(T a); 


I am assuming you are trying to declare a type (you cannot declare a "template variable" without a concrete type).

C++03 doesn't have template typedefs, you need to use a struct as a workaround:

template <typename T>
struct FuncPtr {
    typedef T (*Type)(T a);
};

...

// Use template directly
FuncPtr<int>::Type intf;

// Hide behind a typedef
typedef FuncPtr<double>::Type DoubleFn;
DoubleFn doublef;

C++11 template aliases will eliminate the struct workaround, but presently no compilers except Clang actually implement this.

template <typename T>
typedef T (*FuncPtr)(T a);

// Use template directly
FuncPtr<int> intf;

// Hide behind a typedef
typedef FuncPtr<double> DoubleFn;
DoubleFn doublef;


If you mean create a type for that function, you could do something like this:

template<typename T>
struct Function {
    typedef T (*Ptr)(T);
};

Then use it like

int blah(Function<int>::Ptr a) { }


You can not do that. You can only create function pointers with concrete type.


It's ok on Visual Studio 2015 and on GCC you should use command line option -std=c++11

template<class T> using fpMember = void (T::*)(); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜