Search code examples
c++c++17overloadingstd-invoke

Using std::invoke when a function is overloaded


I am trying to use std::invoke() with an overloaded function:

#include <iostream>
#include <functional>

struct S {
    void foo(int) { }
    void foo(int, int) { }
};

int main()
{
    S s;
    std::invoke(&S::foo, s, 1);
}

but I get an error: 'std::invoke': no matching overloaded function found. It works fine, when there is the only one function with name foo(). Is it possible to use std::invoke() when a function is overloaded?


Solution

  • There are two example solutions:

    std::invoke(static_cast<void(S::*)(int)>(&S::foo), s, 1);
    std::invoke([&s]() { s.foo(1); });