【发布时间】:2013-01-30 14:31:21
【问题描述】:
我想创建一个 std::function 绑定到带有右值参数的成员函数。这是我无法编译的尝试(“xxfunction(154): error C2664: ... You cannot bind an lvalue to an rvalue reference”等等)。
class C
{
public:
void F(std::string &&s)
{
//do something with s
}
C(){}
};
C c;
std::function<void(std::string&&)> pF = std::bind(&C::F,&c,std::placeholders::_1);
//somewhere far far away
pF(std::string("test"));
我做了一些阅读,我认为这与 std::function 没有使用完美转发有关,但我不知道如何让它工作。
编辑:
std::function<void(std::string&)> pF = [&c](std::string&in){c.F(std::move(in));};
这是一个半可行的解决方法,但它并不完美,因为调用 pF 现在将使用左值并移动它。
std::string s("test");
pF(s);
auto other = s; //oops
【问题讨论】:
-
你的代码没有被 GCC 编译好 - liveworkspace.org/code/49qBgA$3 - 也许是你的编译器的错误/功能?
-
clang 3.0 和 gcc 4.7.2 都可以毫无怨言地编译您的代码,这可能是特定于 MSVC 的。你用的是哪个版本?
-
为什么在 lambda 中使用左值引用?
-
@ArneMertz 因为使用右值引用我得到与绑定相同的错误
-
MSVC10 不是完全符合标准的 wrt r-value refs 和 lambdas 以及
std::function实现。所以我想你除了升级别无他法。
标签: c++ rvalue-reference std-function stdbind