Can the 'type' of a lambda expression be expressed?

后端 未结 4 497
小鲜肉
小鲜肉 2020-12-01 04:59

Thinking of lambda expressions as \'syntactic sugar\' for callable objects, can the unnamed underlying type be expressed?

An example:

struct gt {         


        
4条回答
  •  被撕碎了的回忆
    2020-12-01 05:34

    You could use a small class lambda_wrapper<>, to wrap a lambda at low costs. Its much more faster than std::function because there are no virtual function call and a dynamic memory alloc. Wrapper works by deducing the lambda arguments list and return type.

    #include 
    #include 
    #include 
    
    template 
    struct lambda_wrapper : public lambda_wrapper {};
    
    template 
    struct lambda_wrapper {
    private:
        L lambda;
    
    public:
        lambda_wrapper(const L & obj) : lambda(obj) {}
    
        template
        typename std::result_of::type operator()(Args... a) {
            return this->lambda.operator()(std::forward(a)...);
        }
    
        template typename
        std::result_of::type operator()(Args... a) const {
            return this->lambda.operator()(std::forward(a)...);
        }
    };
    template 
    auto make_lambda_wrapper(T&&t) {
        return lambda_wrapper(std::forward(t));
    }
    int main(int argc, char ** argv) 
    {
        auto func = make_lambda_wrapper([](int y, int x) -> bool { return x>y; });
        std::set ss(func);
        std::cout << func(2, 4) << std::endl;
    }
    

提交回复
热议问题