Passing rvalues through std::bind

后端 未结 5 1628
醉话见心
醉话见心 2020-11-29 06:12

I want to pass an rvalue through std::bind to a function that takes an rvalue reference in C++0x. I can\'t figure out how to do it. For example:



        
5条回答
  •  感动是毒
    2020-11-29 06:40

    (This is actually a comment to GMan's answer, but I need some formatting for the code). If generated functor actually is like this:

    struct your_bind
    {
        your_bind(Movable arg0) :
        arg0(arg0)
        {}
    
        void operator()()
        {
            foo(arg0);
        }
    
        Movable arg0;
    };
    
    

    then

    int main()
    {
        auto f = your_bind(Movable());
        f();    // No errors!
    }
    

    compliles without errors. as it's possible to assign and initialize data with rvalue and then pass a data value to rvalue argument of the foo().
    However, I suppose that bind implementation extracts function argument type directly from foo() signature. i.e. the generated functor is:

    struct your_bind
    {
        your_bind(Movable && arg0) :
        arg0(arg0) // ****  Error:cannot convert from Movable to Movable &&
        {}
    
        void operator()()
        {
            foo(arg0); 
        }
    
        Movable&& arg0;
    };
    

    and indeed, this really fails to initialize rvalue data member. Perhaps,the bind implpementation simply does not correctly extract "unreferenced" type from function argument type and uses this type for functor's data member declaration "as is", without trimming &&.

    the correct functor should be:

    struct your_bind
    {
        your_bind(Movable&& arg0) :
        arg0(arg0)
        {}
    
        void operator()()
        {
            foo(arg0); 
        }
    
        Movable arg0; // trim && !!!
    };
    
    
    

提交回复
热议问题