无法使用对*this的引用进行重载



这是我为N2439 ('this'的reff -qualifiers)编写的用于玩gcc-4.8.1+(我认为clang-2.9+也应该这样做)的新功能的busybox:

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中,three 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还是标准的一部分?

我的电脑上没有clang,但是clang说什么?

GCC 4.8.0之前不支持此功能。它应该得到尚未正式发布的GCC 4.8.1的支持。

据我所知,目前唯一支持成员函数引用限定符的主要编译器是Clang。从这个例子中可以看到,您的代码在Clang 3.2上编译得很好。

最新更新