9

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?

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
  • 1
    define it within the class using the template parameter. – OMGtechy Mar 25 '15 at 20:05
  • Does this answer your question? [How to define typedef of function pointer which has template arguments](https://stackoverflow.com/questions/14848924/how-to-define-typedef-of-function-pointer-which-has-template-arguments) – KuhakuPixel Sep 23 '22 at 14:20

1 Answers1

19

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524