请考虑以下代码:
template <typename T>
class A {
public:
template <typename T2>
const T2* DoSomething() { ... }
};
template <typename T>
class B : public A<T> {
public:
const int* DoSomethingElse() {
return this->DoSomething<int>(); // Compiler wants 'template' keyword here:
// return this->template DoSomething<int>();
}
};
Run Code Online (Sandbox Code Playgroud)
为什么不编译?我理解标准的相关部分是14.2/4,但我不确定我理解为什么这不起作用的细节.有人可以打破该部分的措辞来解释为什么这不起作用?另外,您能否(通常)描述在什么情况下可以省略模板关键字?
请注意,在C++ 11下面的代码不会编译:
template <typename T>
class A {
public:
template <typename T2>
const T2* DoSomething() { ... }
};
class B {
public:
scoped_ptr<A<int>> var_;
const int* DoSomethingElse() {
return var_->DoSomething<int>();
}
};
Run Code Online (Sandbox Code Playgroud)
有什么不同?
这是因为 C++ 不是上下文无关语法。
DoSomething通常,编译器会查看先前声明的符号来确定标记序列, <, int,中的尖括号>是关系运算符还是模板名称的一部分。由于这是一个模板,并且尚不知道是否A<T>会专门化,因此编译器不能依赖符号表中的先前声明,并且需要程序员的帮助。