std::invoke 为什么不处理函数重载

2024-04-02

我正在尝试一些 C++17 功能并遇到了 std::invoke。然后我尝试了这段代码:

#include <iostream>
#include <functional>

void f(int i) { std::cout << "fa "; }
void f(float f) { std::cout << "fb "; }

int main() {
    f(0.f);
    std::invoke(f, 0.f);
}

我收到这些错误:

main.cpp: In function 'int main()':
main.cpp:9:23: error: no matching function for call to 'invoke(<unresolved overloaded function type>, float)'
 std::invoke(f, 0.f);

In file included from main.cpp:2:0:
c:/compilers/mingw/lib/gcc/x86_64-w64-mingw32/7.1.0/include/c++/functional:77:5: note: candidate: template<class _Callable, class ... _Args> std::invoke_result_t<_Callable, _Args ...> std::invoke(_Callable&&, _Args&& ...)
 invoke(_Callable&& __fn, _Args&&... __args)
 ^~~~~~

c:/compilers/mingw/lib/gcc/x86_64-w64-mingw32/7.1.0/include/c++/functional:77:5: note:   template argument deduction/substitution failed:
main.cpp:9:23: note:   couldn't deduce template parameter '_Callable'
 std::invoke(f, 0.f);
                   ^

我不是 cpp 专业人士,这只是为了实验目的。我可能永远不会在这种情况下使用它,但为什么它无法解决函数重载?


您甚至可以将示例简化为:

void f(int i) {}
void f(float f) {}

template<typename F>
void foo(F) {}

foo(f); // compilation error here

编译错误的原因很简单:编译器不知道哪个f您将要使用的过载。

为了避免此类错误,您应该帮助编译器推断正确的类型,使用static_cast:

foo(static_cast<void(*)(float)>(f));

对于std::invoke:

std::invoke(static_cast<void(*)(float)>(f), 0.f);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::invoke 为什么不处理函数重载 的相关文章

随机推荐