【发布时间】:2021-09-02 04:32:32
【问题描述】:
试图理解为什么下面的例子编译失败:
#include <functional>
template <typename F>
void f1(F&& f)
{
std::forward<F>(f)("hi");
}
template <typename F>
void f2(F&& f)
{
std::invoke(f, "hi"); // works but can't perfect forward functor
}
template <typename F>
void f3(F&& f)
{
std::invoke<F>(f, "hi");
}
int main()
{
f1([](const char*) {}); // ok
f2([](const char*) {}); // ok
f3([](const char*) {}); // error
}
cppreference 说以下关于std::invoke:
- 使用参数 args 调用 Callable 对象
f。正如INVOKE(std::forward<F>(f), std::forward<Args>(args)...)。仅当std::is_invocable_v<F, Args...>为 true 时,此重载才参与重载解析。
那么为什么f3 不等于f1?
【问题讨论】:
-
@JeJo 我不认为
f1中的std::forward是多余的。F可以是一种行为不同的类型,具体取决于它的operator()是在F的左值还是右值上调用:godbolt.org/z/f3sjcPK14