c++ - 类模板可以是函数吗

标签 c++

我有一个函数

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/

相关文章:

C++ 设计模式 - 仅限成员类

c++ - 从 vector 中删除重复项,递归 C++

c++ - 创建和使用HTML全文搜索索引(C++)

c++ - 子类在 ‘{’ 标记 C++ 之前需要类名

c++ - 初始化的结构是不可变的吗?

c++ - Eclipse 中的无缝 (RSE) 远程项目

c++ - Visual Studio 中的Qt : connecting slots and signals doesn't work

c++ - 如何创建静态常量成员 std::string 数组?

c++ - GCC - 链接到另一个文件夹中的库有效但二进制文件不会运行

C++浮点精度