4

これは、N2439 ('this' の参照修飾子) の gcc-4.8.1+ (clang-2.9+ もこれを行うべきだと思います) の新機能で遊ぶために私が書いたビジーボックスです:

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 を読んでいると、3 つの 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 がインストールされていませんが、clang は何と言っていますか?

4

1 に答える 1

2

この機能は、バージョン 4.8.0 までの GCC ではサポートされていません。まだ正式にリリースされていないGCC 4.8.1 でサポートされているはずです。

私の知る限り、現時点でメンバー関数の参照修飾子をサポートしている唯一の主要なコンパイラは Clang です。この例からわかるように、コードは Clang 3.2 で正常にコンパイルされます。

于 2013-04-02T21:37:58.687 に答える