std :: function and error:没有匹配函数用于调用

ar2*_*015 2 c++ templates c++11 std-function

我正在调用一个基于模板的函数,它在函数和结构之间共享一个类型.这段代码有什么问题?编译时为什么会收到错误?

TEST.CPP

#include <functional>
#include <iostream>

template<typename T>
struct mystruct
{
    T variable;
};

int myfunc(int x)
{
    return 2*x;
}

template<typename T>
T calculate(
    mystruct<T> custom_struct,
    std::function<T(T)> custom_func)
{
    return custom_func(custom_struct.variable);
}

int main()
{
    mystruct<int> A;
    A.variable=6;
    std::cout<<calculate(A,myfunc)<<std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译结果:

test.cpp:25:31: error: no matching function for call to ‘calculate(mystruct<int>&, int (&)(int))’
  std::cout<<calculate(A,myfunc)<<std::endl;
                               ^
Run Code Online (Sandbox Code Playgroud)

Tem*_*Rex 6

没有理由使用std::function包装器.而是使用通用模板参数F

template<typename T, class F>
T calculate(
    mystruct<T> custom_struct,
    F custom_func)
{
    return custom_func(custom_struct.variable);
}
Run Code Online (Sandbox Code Playgroud)

实例

请注意,您也忘记了访问variable呼叫站点的成员.既然你在这里进行泛型编程,你也希望返回类型等于T,或者甚至auto(C++ 14,对于你想要使用的C++ 11,decltype但重复次数太多).