以下程序的输出似乎自相矛盾:
#include <type_traits>
#include <iostream>
#include <functional>
void foo(int&){ std::cout << "called\n"; }
int main() {
int a;
foo(a);
std::cout << std::is_invocable_v<decltype(foo), decltype(a)> << std::endl;
std::invoke(foo, a);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
called
0
called
Run Code Online (Sandbox Code Playgroud)
在我看来,调用一个不可调用的函数?这里发生了什么?
Que*_*tin 59
decltype(a)
是int
.这对应于f
使用int
prvalue调用- 类似于f(7)
.那个确实不编译,因为非const
左值引用不能绑定到prvalue.
你在做什么,而不是在main
呼吁f
与左值,a
以该参考可以绑定就好了.
要获得正确的结果std::is_invocable
,请使用decltype
括号中的表达式:
std::is_invocable_v<decltype(foo), decltype((a))>
// ^ ^
Run Code Online (Sandbox Code Playgroud)