Rafael Baptista
Rafael Baptista

Reputation: 11499

How to typedef a function pointer with template arguments

Consider this:

typedef void (*ExecFunc)( int val );

class Executor
{

  void doStuff() { mFunc( mVal ); }
  void setFunc( ExecFunc func ) { mFunc = func; }

  int           mVal;
  ExecFunc      mFunc;
};

void addOne( int val ) { val = val+1; } // this could be passed as an ExecFunc. 

Very simple. Suppose now that I want to templatize this?

typedef void (*ExecFunc)( int val );    // what do I do with this?

template < typename X > class Executor
{

  void doStuff() { mFunc( mVal ); }
  void setFunc( ExecFunc<X> func ) { mFunc = func; }

  X                mVal;
  ExecFunc<X>      mFunc; // err... trouble..
};

template < typename X > addOne( X val ) { val += 1; }

So how to I create a templatized function pointer?

Upvotes: 9

Views: 7009

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275360

In C++11, you can use this:

template<class X>
using ExecFunc = void(*)(X);

defines ExecFunc<X>.

In C++03, you have to use this instead:

template<class X>
struct ExecFunc {
  typedef void(*type)(X);
};

and use typename ExecFunc<X>::type within Executor.

Upvotes: 19

Related Questions