c++0x: overloading on lambda arity

前端 未结 4 872
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 13:14

I\'m trying to create a function which can be called with a lambda that takes either 0, 1 or 2 arguments. Since I need the code to work on both g++ 4.5 and vs2010(which doe

4条回答
  •  没有蜡笔的小新
    2020-12-09 13:55

    Compile time means of obtaining the arity of a function or a function object, including that of a lambda:

    int main (int argc, char ** argv) {
        auto f0 = []() {};
        auto f1 = [](int) {};
        auto f2 = [](int, void *) {};
    
        std::cout << Arity::value << std::endl; // 0
        std::cout << Arity::value << std::endl; // 1
        std::cout << Arity::value << std::endl; // 2
    
        std::cout << Arity::value << std::endl; // 2
    }
    

    template 
    class Arity {
    private:
        struct Any {
            template 
            operator T ();
        };
    
        template 
        struct Id {
            typedef T type;
        };
    
        template 
        struct Size {
            enum { value = N };
        };
    
        template 
        static Size<0> match (
            F f,
            decltype(f()) * = nullptr);
    
        template 
        static Size<1> match (
            F f,
            decltype(f(Any())) * = nullptr,
            decltype(f(Any())) * = nullptr);
    
        template 
        static Size<2> match (
            F f,
            decltype(f(Any(), Any())) * = nullptr,
            decltype(f(Any(), Any())) * = nullptr,
            decltype(f(Any(), Any())) * = nullptr);
    
    public:
        enum { value = Id(Any())))>::type::value };
    };
    

提交回复
热议问题