c++0x: overloading on lambda arity

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

    I thought the following would work but it doesn't, I'm posting it for two reasons.

    1. To save people the time if they had the same idea
    2. If someone knows why this doesn't work, I'm not 100% sure I understand (although I have my suspicions)

    Code follows:

    #include 
    #include 
    
    template 
    unsigned arity(std::function) { return 0; }
    
    template 
    unsigned arity(std::function) { return 1; }
    
    template 
    unsigned arity(std::function) { return 2; }
    
    // rinse and repeat 
    
    int main() 
    {
        std::function  f = [](int i) { }; // this binds fine
    
        //  Error: no matching function for call to 'arity(main()::)'
        std::cout << arity([](int i) { }); 
    } 
    

提交回复
热议问题