Instantiating C++ lambda by its type

前端 未结 4 1356
野性不改
野性不改 2021-01-01 13:08

I want a way to make functor from function. Now I trying to wrap function call by lambda function and instantiate it later. But compiler says than lambda constructor is dele

4条回答
  •  被撕碎了的回忆
    2021-01-01 13:19

    We can assume that the lambda will always be empty, thus, we can just do a cast from another empty type, since they both have the same memory layout. So we build a wrapper class that makes a default constructible function object:

    template
    struct wrapper
    {
        static_assert(std::is_empty(), "Lambdas must be empty");
        template
        auto operator()(Ts&&... xs) const -> decltype(reinterpret_cast(*this)(std::forward(xs)...))
        {
            return reinterpret_cast(*this)(std::forward(xs)...);
        }
    };
    

    Now a static assert is added to make sure that the lambda is always empty. This should always be the case(since its required to decay to a function pointer), but the standard doesn’t explicitly guarantee it. So we use the assert to at least catch the insane implementation of lambdas. Then we just cast the wrapper class to the lambda since both of them are empty.

    Finally the lambda could be constructed like this:

    template 
    void function_caller()
    {
        wrapper f;
        f();
    }
    

提交回复
热议问题