gpt4 book ai didi

c++ - .template (dot-template) 构造用法

转载 作者:IT老高 更新时间:2023-10-28 14:00:28 28 4
gpt4 key购买 nike

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

我遇到了一段奇怪的代码:

#include <iostream>

template <int N>
struct Collection {
int data[N];

Collection() {
for(int i = 0; i < N; ++i) {
data[i] = 0;
}
};

void SetValue(int v) {
for(int i = 0; i < N; ++i) {
data[i] = v;
}
};

template <int I>
int GetValue(void) const {
return data[I];
};
};

template <int N, int I>
void printElement(Collection<N> const & c) {
std::cout << c.template GetValue<I>() << std::endl; /// doesn't compile without ".template"
}

int main() {
Collection<10> myc;
myc.SetValue(5);
printElement<10, 2>(myc);
return 0;
}

printElement 函数中没有 .template 关键字就不会编译。我以前从未见过这个,我不明白需要什么。试图删除它,我得到了很多与模板相关的编译错误。所以我的问题是什么时候使用这种结构?常见吗?

最佳答案

GetValue是从属名称,因此您需要明确告诉编译器 c 后面的内容是一个函数模板,不是一些成员数据。这就是为什么你需要写template关键字来消除歧义。

没有 template关键字,如下

c.GetValue<I>()  //without template keyword

可以解释为:

//GetValue is interpreted as member data, comparing it with I, using < operator
((c.GetValue) < I) > () //attempting to make it a boolean expression

<被解释为小于运算符,并且 >被解释为大于运算符。上面的解释当然是不正确的,因为它没有意义,因此会导致编译错误。

有关更详细的解释,请在此处阅读接受的答案:

关于c++ - .template (dot-template) 构造用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8463368/

28 4 0