Disambiguating calls to functions taking std::functions

前端 未结 2 601
一向
一向 2021-01-13 08:17

The code below doesn\'t compile on gcc 4.5 because the call to foo is ambiguous. What is the correct way to disambiguate it?

#include 
#         


        
2条回答
  •  走了就别回头了
    2021-01-13 09:15

    I've recently been thinking about a similar problem and when looking around for any known solutions I came across this post and lack of solutions for resolving

    An alternative solution is to abstract over the functor as a template argument and use decltype to resolve its type. So, the above example would become:

    #include 
    #include 
    using namespace std;
    
    template
    auto foo(F t) -> decltype(t(1,2))
    {
        t(1, 2);
    }
    
    template
    auto foo(F t) -> decltype(t(2)) 
    {
        t(2);
    }
    
    int main()
    {
         foo([](int a, int b){ cout << "a: " << a << " b: " << b << endl;});
    }
    

    This works as expected with gcc 4.5.

提交回复
热议问题