问题描述
以下程序的输出似乎自相矛盾:
The following program's output seems to contradict itself:
#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);
}
输出为:
called
0
called
在我看来哪个调用了一个无法调用的功能?
Which seems to me to be invoking a function that is not invocable? What is going on here?
推荐答案
。这对应于使用 int
prvalue 调用 f
-类似 f(7)
。那确实不能编译,因为非 const
左值引用不能绑定到prvalue。
decltype(a)
is int
. This corresponds to invoking f
with an int
prvalue -- something like f(7)
. That one indeed doesn't compile, because a non-const
lvalue reference cannot bind to a prvalue.
什么而是在 main
中用 lvalue ,<$ c调用 f
$ c> a ,引用可以很好地绑定到它。
What you're doing instead in main
is calling f
with an lvalue, a
, to which the reference can bind just fine.
要从 std获得正确的结果: :is_invocable
,通过添加括号使用 decltype
的表达式形式:
To get the correct result from std::is_invocable
, use the expression form of decltype
by adding parentheses:
std::is_invocable_v<decltype(foo), decltype((a))>
// ^ ^
这篇关于std :: is_invocable为false,但std :: invoke有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!