【问题标题】:How to typedef a function pointer with template arguments如何使用模板参数对函数指针进行类型定义
【发布时间】:2015-03-25 20:03:30
【问题描述】:

考虑一下:

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. 

非常简单。现在假设我想将这个模板化?

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; }

那么如何创建模板化函数指针呢?

【问题讨论】:

  • 使用模板参数在类中定义它。

标签: c++ templates function-pointers


【解决方案1】:

在 C++11 中,你可以这样使用:

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

定义ExecFunc&lt;X&gt;

在 C++03 中,你必须改用这个:

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

并在Executor 中使用typename ExecFunc&lt;X&gt;::type

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多