Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer as a template

Tags:

c++

How to write a function pointer as template?

template <typename T>
T (*PtrToFunction)(T a); 
like image 732
user562549 Avatar asked Dec 13 '22 09:12

user562549


2 Answers

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;
like image 134
Alex B Avatar answered Dec 31 '22 16:12

Alex B


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) { }
like image 23
Seth Carnegie Avatar answered Dec 31 '22 16:12

Seth Carnegie