c++0x: overloading on lambda arity

前端 未结 4 848
被撕碎了的回忆
被撕碎了的回忆 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:42

    A lambda function is a class type with a single function call operator. You can thus detect the arity of that function call operator by taking its address and using overload resolution to select which function to call:

    #include 
    
    template
    void do_stuff(F& f,R (F::*mf)() const)
    {
        (f.*mf)();
    }
    
    template
    void do_stuff(F& f,R (F::*mf)(A1) const)
    {
        (f.*mf)(99);
    }
    
    template
    void do_stuff(F& f,R (F::*mf)(A1,A2) const)
    {
        (f.*mf)(42,123);
    }
    
    template
    void do_stuff(F f)
    {
        do_stuff(f,&F::operator());
    }
    
    int main()
    {
        do_stuff([]{std::cout<<"no args"<

    Be careful though: this won't work with function types, or class types that have more than one function call operator, or non-const function call operators.

提交回复
热议问题