【问题标题】:c++, pointer to function + function templatesc++,指向函数+函数模板的指针
【发布时间】:2016-10-18 11:17:54
【问题描述】:

有一个稍微“复杂”的代码,其中 A 类存储了一个指向函数的指针(初始化为 F1)。函数 F1 调用 F2 并将 F3 作为模板参数传递。

template <typename T>
using cfunction = T(*)(T, T);

template <typename T>
T F3(const T a, const T b) {return a * b;}

template <typename T, typename Function>
T F2(Function func, const T a, const T b) {return func(a, b);}

template <typename T>
T F1(const T a, const T b) { return  F2(F3<T>(a, b), a, b);}

template <typename T>
class A {
    public:
    cfunction <T> X;

    A() : X(&F1) {}
    A(const cfunction <T> &pX) : X(pX) {};
    virtual ~A() {};
};

int main() {
    A<double> b(F1<double>);
    return 0;
}

很遗憾,出现以下错误:

error: 'func' cannot be used as a function

问题出在哪里?还有什么方法可以避免将 a,b 作为 F2 和 F3 参数传递吗?感谢您的帮助...

【问题讨论】:

    标签: c++ templates parameter-passing function-pointers


    【解决方案1】:

    改为:

    template <typename T>
    T F1(const T a, const T b) { return  F2(F3<T>, a, b);}
                                            ^^^^^
    

    【讨论】:

    • 感谢您的快速解决方案 :-)
    猜你喜欢
    • 1970-01-01
    • 2015-04-26
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 2010-09-13
    相关资源
    最近更新 更多