我正在调用基于模板的函数,该功能在函数和结构之间共享类型。此代码有什么问题?为什么我在编译时会收到错误?
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;
}
编译器结果:
test.cpp:25:31: error: no matching function for call to ‘calculate(mystruct<int>&, int (&)(int))’
std::cout<<calculate(A,myfunc)<<std::endl;
^
没有理由使用std::function
包装器。而是使用一般模板参数F
template<typename T, class F>
T calculate(
mystruct<T> custom_struct,
F custom_func)
{
return custom_func(custom_struct.variable);
}
实时示例
请注意,您还忘记了在呼叫站点上访问variable
成员。由于您在这里进行通用编程,因此您还希望返回类型等于T
,甚至等于auto
(C 14,对于C 11,您都需要使用decltype
,但这太多了)。
您的代码有点混乱,但总有一个解决方案。
#include <functional>
#include <iostream>
template<typename T>
struct mystruct
{
T variable;
};
const int myfunc(const 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<int>(A,myfunc)<<std::endl;
return 0;
}
return custom_func(custom_struct)
只是一个问题,您要通过该结构传递variable
成员并添加calculate<int>
而不是calculate
。
您可以在此处尝试/测试新代码:http://cpp.sh/33cpn
template<typename T>
int calculate(
mystruct<T> custom_struct,
std::function<T(T)> custom_func);
编译器将尝试从std::function<T(T)>
和mystruct<T>
推导T
,但功能指针的扣除失败。一种解决方案是通过使其成为未折叠的上下文来禁用std::function<T(T)>
的模板扣除:
template <typename T> struct identity { using type = T; };
template <typename T> using identity_t = typename identity<T>::type;
template<typename T>
int calculate(
mystruct<T> custom_struct,
identity_t<std::function<T(T)>> custom_func)
{
return custom_func(custom_struct.variable);
}
尽管它使函数签名有些丑陋,但您仍然可以推导T
,因此您只需致电calculate(A,myfunc)
而不是calculate<int>(A,myfunc)
。
但是,在这种情况下,您应该使用Templaterex的解决方案,因为std::function
带有一堆开销,除非您想将其存储在某个地方。
您错误地将custom_struct
传递给calculate()
中的custom_func
。
尝试通过custom_struct.variable
:
template<typename T>
int calculate(
mystruct<T> custom_struct,
std::function<T(T)> custom_func)
{
return custom_func(custom_struct.variable);
}
也在Ideone上