【发布时间】:2017-08-04 19:59:48
【问题描述】:
我正在尝试一些 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 专业人士,这只是为了实验目的。我可能永远不会在这种情况下使用它,但为什么它无法解决函数重载?
【问题讨论】:
-
这与
invoke无关。您使用的名称f没有指定您的意思是哪个f。绕过它的方式有点难看:static_cast<void(*)(int)>(f). -
谢谢,很奇怪,就像我在答案中回复的那样,我认为它会更灵活。这有点不方便。
标签: c++