Different overloads with std::function parameters is ambiguous with bind (sometimes)

前端 未结 1 1817
遇见更好的自我
遇见更好的自我 2021-01-06 11:42

I have two overloads of a function foo which take different std::functions which results in an ambiguity issue for the latter when used with the re

相关标签:
1条回答
  • 2021-01-06 12:35

    The problem exists in how bind is allowed to be called. As cppreference states

    If some of the arguments that are supplied in the call to g() are not matched by any placeholders stored in g, the unused arguments are evaluated and discarded.

    In other words, you need to pass at least as many arguments as the underlying callable expects.

    This means that the following is valid

    int f();
    auto b = std::bind(f);
    b(1, 2, 3); // arguments aren't used
    

    So saying

    auto b = std::bind(ret_int)
    b(1);
    

    Works, with the 1 discarded, therefore the following is valid, and overload selection becomes ambiguous

    std::function<void(int)> f = std::bind(ret_int);
    

    The inverse is not true, however

    std::function<int()> f = std::bind(take_int);
    

    because take_int cannot be called with no arguments.

    Takeaway: lambda > bind

    0 讨论(0)
提交回复
热议问题