【发布时间】:2012-01-17 19:13:05
【问题描述】:
可能重复:
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 关键字就不会编译。我以前从未见过这个,我不明白需要什么。试图删除它,我得到了很多与模板相关的编译错误。所以我的问题是什么时候使用这种结构?常见吗?
【问题讨论】:
-
只是为了记录,它不是
.template(单个点模板结构),而是两个标记,一个点,后跟template关键字。写c. template GetValue<I>也是合法的。template绑定到成员函数GetValue,而不是点。 -
这个问题 - 虽然是重复的 - 很有用。只是搜索模板会带来很多噪音。 “dot-template”短语是我最后找到的。