Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Rafael Baptista Avatar asked Mar 25 '15 20:03

Rafael Baptista


1 Answers

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.

like image 194
Yakk - Adam Nevraumont Avatar answered Sep 21 '22 09:09

Yakk - Adam Nevraumont