我有一个函数
double function(const infocontainer&);
它作为参数传递给另一个函数。
void bigfunction(std::ostream& os, const std::string& s, double F(const infocontainer&), const infocontainer a, const infocontainer b)
{
os << F(a) << F(b) << std::endl;
}
当我使用模板时,虽然我需要给 F 信息容器 a 和 b 的地址。为什么?
template <class F> void bigfunction(std::ostream& os, const std::string& s, F, const infocontainer a, const infocontainer b)
{
os << F(&a) << F(&b) << std::endl;
}
这就是我在 MAIN
中调用函数的方式
bigfunction(std::cout, "name", function, cont_a, cont_b);
最佳答案
在您的模板定义中,F
是一个类型名称,而不是函数指针。因此,F(x)
符号将被编译器解释为尝试强制转换 x
以键入F
。它不是函数调用,而是 C++ 风格的转换。这与您尝试做的完全不同。这就是为什么你“必须”使用 &a
和 &b
作为参数,因为编译器需要 pointer 参数来转换为函数指针类型 F
。当然,所有这些都毫无意义。
你要做的就是给你的函数参数命名
template <class F> void bigfunction(std::ostream& os, const std::string& s, F f,
const infocontainer a, const infocontainer b)
(为什么一开始就省略了名字?)
然后在没有任何&
os << f(a) << f(b) << std::endl;
关于c++ - 类模板可以是函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773859/