无法重载引用* this

时间:2013-04-02 21:37:04

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

这是我写的一个忙箱,用于播放N2439的gcc-4.8.1 +中的新功能(我认为clang-2.9 +也应该这样做)(对于'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 bug还是标准的一部分?

我的电脑上没有铿锵声,但铿锵说什么?

1 个答案:

答案 0 :(得分:2)

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

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