C ++模板-基于参数编译成员函数

问题描述 投票:0回答:1

[假定类具有成员函数,该成员函数应接受double(double)函数或以“ MyStructFunc”公共成员函数作为参数的类实例:

#include<functional>
#include <type_traits>
struct Caller
{
    // (1.)
    double call(std::function<double(double)> func) { return func(1); }

    // (2.)
    template<typename T>
    double call(const T& S) { return S.MyStructFunc(2); }
};

因此,例如,我们可以通过

double myFunc(double x) { return x * x * x; }

struct myStruct
{
    double MyStructFunc(double x) { return x * x; }
};

像这样:

int main()
{
    Caller c;
    myStruct ms;
    c.call(myFunc);
    c.call(ms);
}

不幸的是,我得到一个错误。你能帮我使它工作吗?谢谢您的帮助!

c++ templates c++14 typetraits
1个回答
0
投票
功能指针不是std::function,因此您的模板方法更合适。
© www.soinside.com 2019 - 2024. All rights reserved.