【问题标题】:Unable to overload with references to *this无法重载对 *this 的引用
【发布时间】:2013-04-02 21:37:03
【问题描述】:

这是我写的一个busybox,用于使用gcc-4.8.1+中的新功能(我认为clang-2.9+也应该这样做),用于N2439('this'的引用限定符):

class Foo
{
public:
  Foo(int i) : _M_i(i) { }
  int bar() & { return _M_i /= 2; }
  int bar() const & { return _M_i; }
  int bar() && { return 2 * _M_i; }

private:
  int _M_i = 42;
};

int
main()
{
  Foo ph(333);
  ph.bar();

  const Foo ff(123);
  ff.bar();

  Foo(333).bar();
}

在阅读标准 8.3.5 时,我认为这三个 bar() 方法应该是可重载的。我得到一个链接器错误:

[ed@localhost ref_this]$ ../bin/bin/g++ -std=c++11 -o ref_this ref_this.cpp
/tmp/ccwPhzqr.s: Assembler messages:
/tmp/ccwPhzqr.s:73: Error: symbol `_ZN3Foo3barEv' is already defined

如果我注释掉int bar() const &,我将无法解析ff.bar();

[ed@localhost ref_this]$ ../bin/bin/g++ -std=c++11 -o ref_this ref_this.cpp
ref_this.cpp: In function ‘int main()’:
ref_this.cpp:26:10: error: no matching function for call to ‘Foo::bar() const’
   ff.bar();
          ^
ref_this.cpp:26:10: note: candidates are:
ref_this.cpp:11:7: note: int Foo::bar() &
   int bar() & { return _M_i /= 2; }
       ^
ref_this.cpp:11:7: note:   no known conversion for implicit ‘this’ parameter from ‘const Foo’ to ‘Foo&’
ref_this.cpp:13:7: note: int Foo::bar() &&
   int bar() && { return 2 * _M_i; }
       ^
ref_this.cpp:13:7: note:   no known conversion for implicit ‘this’ parameter from ‘const Foo’ to ‘Foo&&’

这是 gcc 错误还是标准的一部分?

我不在我的电脑上,但 clang 说什么?

【问题讨论】:

标签: c++ c++11 reference this rvalue


【解决方案1】:

GCC 版本 4.8.0 之前不支持此功能。 It should be supported by GCC 4.8.1,尚未正式发布。

据我所知,目前唯一支持成员函数引用限定符的主要编译器是 Clang。从this example 可以看出,您的代码在 Clang 3.2 上编译良好。

【讨论】:

  • 对此的参考是 just added 到 g--4.8.1 和 gcc 主干。我知道释放是潮湿的,没有多少人拥有它,但它就在那里。
  • 您的 LWS 示例显示了一堆错误。这是gcc吗?你也有 clang 版本吗?
  • 谢谢,我明白了。我去看看 LWS。我认为 IDEone 有相当老的 gcc。
  • @emsr:IDEone 和 LWS 都有适用于 C++11 的 GCC 4.7.2,尽管 LWS 也有许多其他 C++ 编译器。
  • @Xeo 谢谢,我很高兴他们升级了版本。我得试试我的一些测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多