成员函数模板不会在 clang 上编译,但在 GCC 上编译

Member function template doesn't compile on clang, but does on GCC

本文关键字:编译 但在 GCC clang 函数模板 成员      更新时间:2023-10-16

在下面的代码中,我有一个名为 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() 的非成员函数模板调用相同的代码(与 zipcode::get_postbox 相同)不会导致错误!

若要亲自查看并使用它,下面是编译器资源管理器中的代码: 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>();
}

使用如下所示的模板成员函数时,需要使用 template 关键字:

my_postoffice.template get_postbox<K>()

po.template get_postbox<D>()

c.f. 在这里:代码的 http://ideone.com/W0owY1在这里:我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?有关何时使用模板关键字的确切说明

相关文章: