Function pointer as a template

advertisements

How to write a function pointer as template?

template <typename 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;