以下代码在 Visual Studio 2013 下编译,在 gcc/clang(所有测试版本)下编译失败。
铿锵:error: use 'template' keyword to treat 'write' as a dependent template name
海湾合作委员会:error: expected primary-expression before ‘int’
这两个错误都发生在代码中指示的位置
template <typename Itr>
struct A {
template <typename Other>
void write(Other x) {}
};
template <class T>
struct B {
A<T>& a;
B(A<T>& a) : a(a) {
// error: use 'template' keyword to treat 'write' as a dependent template name
a.write<int>(5);
}
};
int main() {
A<int> a;
// Fine
a.write<int>(5);
B<int> b(a);
}
经验告诉我 Visual Studio 可能是错误的,但我不确定为什么在 A<T>
时编译失败。已完全指定,我只想调用我指定类型的模板方法。
最佳答案
来自[temp.names],强调我的:
When the name of a member template specialization appears after
.
or->
in a postfix-expression or after a nested-name-specifier in a qualified-id, and the object expression of the postfix-expression is type-dependent or the nested-name-specifier in the qualified-id refers to a dependent type, but the name is not a member of the current instantiation (14.6.2.1), the member template name must be prefixed by the keywordtemplate
. Otherwise the name is assumed to name a non-template.
在这里,write
是出现在 .
之后的成员模板特化在后缀表达式中,以及 a
与类型相关(取决于 T
),并且 a
不是当前实例化的成员(将是 B<T>
),因此它必须以 template
为前缀。 gcc 和 clang 拒绝此代码是正确的,因为它应该被视为 write
是非模板并且 <
是一个运算符 - 这是无效的。
关于c++ - 依赖模板可以使用 Visual Studio 编译,但使用 clang/gcc 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32387428/