【问题标题】:Member function template doesn't compile on clang, but does on GCC成员函数模板不能在 clang 上编译,但在 GCC 上可以
【发布时间】:2017-01-26 14:34:14
【问题描述】:

在下面的代码中,我有一个名为zipcode 的类模板,它有一个名为get_postbox 的成员函数模板。它可以在 GCC 中编译,但不能在 clang 3.9 中编译。为什么 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>();
}

【问题讨论】:

  • 你需要return my_postoffice.template get_postbox&lt;K&gt;();
  • @songyuanyao 不错!那行得通。谢谢!
  • 查看更多详情here

标签: c++ clang


【解决方案1】:

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

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? 了解何时使用模板关键字的确切说明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2015-09-22
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多