【发布时间】:2014-10-11 14:18:02
【问题描述】:
我正在使用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() 时,或者如果 lambda 采用 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.
我的问题是:
- 当 lambda 采用右值引用时,为什么不能调用(不会编译)
bind_fun()? - 在这里使用引用和右值引用作为 lambda 的参数有什么区别?
【问题讨论】:
-
std::bind将绑定的参数作为左值传递,因此它与右值引用不匹配。