Function Index as a Template

How to write a function pointer as a template?

template <typename T> T (*PtrToFunction)(T a); 
+4
source share
4 answers

I assume that you are trying to declare a type (you cannot declare a "template variable" without a specific type).

C ++ 03 does not have typedefs templates, you need to use 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 eliminate the struct workaround, but currently no compilers other than Clang really 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; 
+8
source

If you want to create a type for this function, you can do something like this:

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

Then use it like

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

You cannot do this. You can only create function pointers with a specific type.

0
source

This is normal in Visual Studio 2015 and in GCC, you should use the command line option -std=c++11

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

All Articles