c++ - 带有模板参数的函数的编译问题

标签 c++ templates

大家好,我有一个编译错误,我似乎无法通过。

这是我所做的:我声明了一个类 2 的对象,并将其函数称为“function2”。反过来,这个函数声明了一个 class1 的对象并调用它的函数“function1”。现在,此代码在此时出现编译错误(无法正确调用“function1”):

错误:')' 标记前应为主表达式

但是,如果我取消注释无用的“function1”,代码就会编译。我觉得这很困惑,因为这不是被调用的函数,根本不应该影响。

#include <iostream>
using namespace std;

template<int parameter1>
class class1 {
    public:

    template < int parameter2 > void function1() {
        cout << "We do useful things here" << endl;
    }
};

template < int parameter3 >
class class2 {
    public:

    //template < char a, char b > bool function1() {
    //    cout << "Useless definition (?)" << endl;
    //}

    void function2() {
        class1 < parameter3 > an_instance_of_class1;
        an_instance_of_class1.function1 < 999 > ();
    }
};

int main(int argc, char** argv) {
    class2 < 99 > an_instance_of_class2;
    an_instance_of_class2.function2();
}

有人知道我错过了什么吗?提前致谢。

编译器版本:

$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

最佳答案

你需要使用.template:

an_instance_of_class1.template function1 < 999 > ();

查看已接受的答案 here了解更多详情。

关于c++ - 带有模板参数的函数的编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12107494/

相关文章:

c++ - 模板和重载运算符 <<

c++ - VBScript 和 C++ 之间 wuapi 的无法解释的差异

c++ - std::list::clear 是否使 std::list::end 迭代器无效?

c++ - 为什么不允许 double 作为非类型模板参数?

c++ - 抛出不能正常工作

c++ - 无权访问模板模板参数

c++ - 使用文本文件 c++ 中的名称创建变量或对象

c++ - 继承抽象模板类

c++ - 如何在boost property_tree前面加一个节点

templates - 如何为 SQL Server 2005 Reporting Services 报告创建模板?