gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:56 25 4
gpt4 key购买 nike

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

这是我所做的:我声明了一个类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com