4

How to write a function pointer as template?

template <typename T>
T (*PtrToFunction)(T a); 
2
  • 3
    That would amount to a "template typedef", which doesn't exist. In C++11 you have template aliases, but I'm not sure if they cover that situation. Commented Sep 3, 2011 at 14:19
  • 1
    If your application's size warrants it, use a more general functor object like Boost.Function which allows you to use any kind of callable object, not just function pointers. If you're writing a small app, don't bother. Commented Sep 3, 2011 at 14:36

4 Answers 4

8

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Just updating this old entry to mention that as of GCC 4.7, GCC now supports template aliases.
5

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) { }

Comments

0

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

Comments

0

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::*)(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.