1

私はstd::bind右辺値参照で遊んでいますが、それがどのように機能するのかまだわかりません.次のコードがあります:

class Dog {
 public:
   Dog(const string &name) : name_(name) {
     cout << "Dog::ctor" << endl;
   }
   string GetName() {
     return name_;
   }

 private:
   string name_;
};

auto bind_fun = bind([](Dog &&d){ cout << d.GetName() << endl; }, Dog("DogABC"));
bind_fun(); 

をコメントアウトするbind_fun()場合、またはラムダがではDog&なくかかる場合Dog&&、コードは期待される出力で正常に実行されます。をコメント解除したままにするbind_fun()と、次のコンパイル時エラーが発生します。

test3.cpp:109:3: error: no matching function for call to object of type 'std::__1::__bind<<lambda at test3.cpp:108:17>, Dog>'
  f();
  ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/functional:1749:9: note: candidate template ignored: substitution failure [with _Args = <>]: implicit instantiation of undefined template
      'std::__1::__bind_return<<lambda at test3.cpp:108:17>, std::__1::tuple<Dog>, std::__1::tuple<>, false>'
        operator()(_Args&& ...__args)
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/functional:1758:9: note: candidate template ignored: substitution failure [with _Args = <>]: implicit instantiation of undefined template
      'std::__1::__bind_return<const <lambda at test3.cpp:108:17>, const std::__1::tuple<Dog>, std::__1::tuple<>, false>'
        operator()(_Args&& ...__args) const
        ^
1 error generated.

私の質問は次のとおりです。

  1. bind_fun()ラムダが右辺値参照を取るときに呼び出せない(コンパイルしない)のはなぜですか?
  2. ここでラムダの引数として参照と右辺値参照を使用することの違いは何ですか?
4

1 に答える 1