2014-10-11 3 views
1

내가 std::bind과를 rvalue 참조와 함께 연주하고,하지만 난 아직도, 나는 다음과 같은 코드가 작동하는 방법을 알아낼 수 없습니다 :표준 : 바인드() : 인수로를 rvalue 참조와 바인드 람다

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(); 

을 주석으로 처리하거나 람다가 Dog&&이 아닌 Dog&을 사용하는 경우 코드가 예상 출력으로 올바르게 실행됩니다.

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. 

내 질문

은 다음과 같습니다 : bind_fun() 호출 할 수없는 이유는 무엇

  1. 가 (컴파일되지 않습니다) 람다가를 rvalue 참조를 취하면 bind_fun(), 주석 다음 컴파일 타임 오류가 남아?
  2. 여기에서 람다에 대한 참조로 참조 및 값 참조를 사용하는 것의 차이점은 무엇입니까?
+0

'std :: bind'는 바인딩 된 인수를 lvalues로 전달하므로 rvalue 참조와 일치하지 않습니다. –

답변

2

std::bind의 사양은 다소 밀집되어 있습니다. 간단히 말해, 바운드식이 아닌 reference_wrapper이 아닌 바인드식이 std::forward<Vi>(tid)으로 바운드 함수에 전달됩니다. 여기서 ViTiD cv &이고 cv은 호출 랩퍼의 cv 한정자이고 TiD은 형식입니다 decay_t<Ti>, Ti은 실제로 bind에 전달되는 유형이고 tidstd::forward<Ti>(ti)에서 구성된 유형의 왼쪽 값이고 tibind에 전달 된 인수입니다.

통화에 적용하면 TiDog이고 tiDog("DogABC")입니다. 그래서 TiDDog이며, Vistd::forward<Vi>(Tid)가 좌변 이며, 당신의 람다가를 rvalue 참조 매개 변수를, 그리고를 rvalue 참조 매개 변수는 좌변에 결합 할 수 없기 때문에 컴파일러가 불평 즉, cv Dog &이다.

+0

와우는 상당히 복잡하지만 나에게 의미가 있습니다. 정말 고마워요! – neevek