【问题标题】:std::function pointer to member function taking rvalue arguement MSVC2010 SP1std::function 指向采用右值参数的成员函数的指针 MSVC 2010 SP1
【发布时间】: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


【解决方案1】:

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

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

编辑:

注意:虽然被接受,但这个答案并不能解决手头的问题,因为有缺陷的不是 std::bind 而是 MSVC10 的 std::function 实现。但是,该建议导致了解决方法,因此被PorkyBrain 接受。

【讨论】:

  • 那么@PorkyBrain 可以发布他的实际解决方案作为答案并接受那个吗?
猜你喜欢
  • 2017-08-27
  • 1970-01-01
  • 2013-05-07
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多