std::invoke() does not support overloaded functions

Let's look at a piece of code first:

void foo(int a) {

}
void foo(double d) {

}

template <typename T>
void my_invoke(T a) {
  a(2);
}
int main() {
  my_invoke(foo);
}

Compiling this code will prompt: no matching function for call to 'my_invoke(<unresolved overloaded function type>)'

The general meaning of the translation is that you don’t know which foo() to call. This is because although foo here is a variable value corresponding to a function type, due to the existence of function overloading, the complete function type cannot be inferred only from the function name. This is where function types differ from normal types. To give a simpler example, since other variables cannot have the same name (in any context, only one variable is valid), you can use decltype to get its type, but the function name is different, and there can be countless variables in one context. function of the same name.

This is also different from SFINAE. SFINAE is a process of specialization of multiple class templates. It does not mean that two foo can be used to try to call my_invoke in turn.

To compile, just complete the function type:

my_invoke(static_cast<void(*)(int)>(foo));

Guess you like

Origin blog.csdn.net/cyfcsd/article/details/130010607