How can I make the storage of C++ lambda objects more efficient?

后端 未结 5 1016
猫巷女王i
猫巷女王i 2021-02-05 07:16

I\'ve been thinking about storing C++ lambda\'s lately. The standard advice you see on the Internet is to store the lambda in a std::function object. However, none of this adv

5条回答
  •  佛祖请我去吃肉
    2021-02-05 07:28

    The problem is that std::function doesn't use move semantics and copies the lambda around while initializating. It's a bad implementation by MS.

    Here is a little trick you can use to get around the problem.

    template
    class move_lambda
    {
        T func_;
    
    public:
        move_lambda(T&& func) : func_(std::move(func)){}            
        move_lambda(const move_lambda& other) : func_(std::move(other.func_)){} // move on copy 
        auto operator()() -> decltype(static_cast(0)()){return func_();}
    };
    
    template 
    move_lambda make_move_lambda(T&& func)
    {
        return move_lambda(std::move(func));
    }
    

    usage:

    int main()
    {
        Simple test( 5 );
    
        std::function f(make_move_lambda(
            [test] ()
            {
                return test.Get();
            }));
    
        printf( "%d\n", f() );
    }
    

提交回复
热议问题