【问题标题】:how to pass function pointer as a template parameter如何将函数指针作为模板参数传递
【发布时间】:2011-12-14 08:57:48
【问题描述】:

第二行编译得很好,但第三行给我一个错误

int (* const f)() = ff;
cout << typeid(replace<int (*)(), int, char>::type).name() << endl;
cout << typeid(replace<f, int, char>::type).name() << endl;

test.cpp:3:25: error: the value of ‘f’ is not usable in a constant expression 
test.cpp:1:15: note: ‘f’ was not declared ‘constexpr’
test.cpp:3:37: error: template argument 1 is invalid

【问题讨论】:

    标签: c++ templates function parameters


    【解决方案1】:

    只有当形参是非类型形参时,模板实参才可以是函数指针。但遗憾的是,C++11 甚至还不允许使用各种常量表达式来计算模板参数。对于非类型指针或引用,只允许传递另一个模板参数的值或直接获得的函数或对象的地址,而不是先将其存储在const/constexpr变量中。

    这个限制很可能会在下一个 C++ 版本中取消。

    【讨论】:

    • @sehe 请不要那么快解决问题。你删除了我添加的一段:-)
    • 删除了我的答案,这解释了上述失败的原因——我错了。
    • @JohannesSchaub-litb:对不起!你可以回滚,不是吗? (你不能真的说“我删除了它”——我没有看到关于并发编辑的警告。这意味着你一定错过了警告?)无论如何,我会让你修复这是为了避免进一步的不幸。
    【解决方案2】:

    你可以使用模板接口代替函数指针:

    template<class T>
    class IMyInterface{
    public:
     virtual void doSomething(const T& arg) =0;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多