2

我想创建一个 std::function 绑定到采用右值参数的成员函数。这是我无法编译的尝试(“xxfunction(154): error C2664: ... You cannot bind an lvalue to a 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
4

1 回答 1

0

您的std::bind实现似乎不支持通过占位符进行完美转发,但是由于您拥有 C++11 并且std::bind无论如何都很难看,请使用 lambda:

std::function<void(std::string&&)> pF 
  = [&c](std::string&& str)
{ 
  c.F(std::move(str)); 
};

编辑:

Note: Although accepted, this answer is not a solution to the problem at hand, because it is not std::bind but MSVC10's std::function implementation that is flawed. However, the suggestion has led to a workaround and therefore was accepted by PorkyBrain.

于 2013-01-30T14:42:11.820 回答