c++ - 依赖模板可以使用 Visual Studio 编译,但使用 clang/gcc 失败

标签 c++ templates c++11

以下代码在 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 keyword template. 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/

相关文章:

c++ - 重载 'swap(float&, float&)' 的调用不明确

python - 你在哪里存储 jinja 中的变量?

c++ - 用于存储 128 位数据的 Cpp 变量/结构

c++ - 如何将平面网格转换为CGAL中的排列

c++ - 如果我重新定义 sqrt 函数,为什么使用 std::sqrt 会失败?

C++11:unordered_map/set 是否保证遍历顺序为插入顺序?

c++ - qmake在命令行中分配变量

c++递归数组解释

c++ - gcc 编译器标志以抑制编译期间模板错误的模板扩展?

c++ - 这是对 std::bind 的错误使用还是编译器错误?