c++ - 成员函数模板不在 clang 上编译,但在 GCC 上编译

标签 c++ clang

在下面的代码中,我有一个名为zipcode 的类模板,它有一个名为get_postbox 的成员函数模板。它在 GCC 中编译但不在 clang 3.9 中编译。为什么 clang 不接受这个代码?

在 clang 中我得到这个错误:

<source>:34:41: error: expected expression
return my_postoffice.get_postbox<K>();
^

此外,从名为 non_member_function_template()non-member 函数模板调用相同的代码(与 zipcode::get_postbox 相同)不会导致错误!

要亲自查看并使用它,这里是 Compiler Explorer 中的代码:https://godbolt.org/g/MpYzGP


代码如下:

template <int K>
struct postbox
{
    int val() const 
    {
      return K;
    }
};

template <int A, int B, int C>
struct postoffice
{
  postbox<A> _a;

  template<int I>
  postbox<I> get_postbox()
  {
    switch( I )
    {
      case A: return _a;
    }
  }
};

template <typename PO>
struct zipcode
{
  PO my_postoffice;

  template<int K>
  postbox<K> get_postbox()
  {
    // The error is on this line
    return my_postoffice.get_postbox<K>();
  }
};

// Here's a function template that isn't a member, and it compiles.
template<int D>
int non_member_function_template()
{
  postoffice<123,345,678> po;
  auto box = po.get_postbox<D>();
  return box.val(); 
}

int test_main()
{
  return non_member_function_template<123>();
}

最佳答案

像这样使用模板成员函数时需要使用模板关键字:

my_postoffice.template get_postbox<K>()

po.template get_postbox<D>()

比较这里:http://ideone.com/W0owY1对于代码 在这里:Where and why do I have to put the "template" and "typename" keywords?有关何时使用模板关键字的确切说明

关于c++ - 成员函数模板不在 clang 上编译,但在 GCC 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875820/

相关文章:

c++ - clang 3.5 : Detecting a gobal function doesn't exist using SFINAE

c++ - 在 Windows 中配置 CMake 以从命令行使用 clang 以获得现代 OpenMP 支持

c - 为什么寄存器数组名称可以分配给指针变量而不会出现编译器错误?

C++ Vector 实现分配新对象

c++ - 链表 - 当我使用 -> 打印函数时程序中断

c++ - 位字段类型是否需要相同?

c++ - 调用模板函数时编译器错误

c++ - 静态局部变量和静态局部对象初始化

linux - 使用非 gcc 编译 linux 内核

clang - 如何在 LLVM IR 中调用 C++ 函数?