Search code examples
c++operator-overloadingstd-functionexplicit

how to make a operator have an explicit parameter c++


consider some code:

void foo() { }
bool bar() { return true; }

struct S
{
    void operator=(std::function<void()> f){f();};
    void operator=(std::function<bool()> f){f();};      
};

int main() {
    S s;
    s = foo; // ok
    s = bar; // error: use of overloaded operator '=' is ambiguous
}    

How can I make this example unambiguous?


Solution

  • The problem you're running into is that std::function<void(Args...)> is allowed to discard return types - so both std::function<void()> and std::function<bool()> can be constructed from a bool(*)(). The latter will forward through the return from bar, but the former will just discard it. That's perfectly valid behavior, but causes this to be ambiguous.

    What you probably want is to avoid std::function altogether:

    template <class F>
    void operator=(F f) { f(); }