【发布时间】:2020-06-07 12:07:05
【问题描述】:
#include <iostream>
#include <utility>
template<typename T>
void f1(T&& t) // &&
{
if constexpr (std::is_function_v<typename std::remove_pointer_t<T>>)
std::cout << "function" << std::endl;
else
std::cout << "not a function" << std::endl;
}
template<typename T>
void f2(T& t) // &
{
if constexpr (std::is_function_v<typename std::remove_pointer_t<T>>)
std::cout << "function" << std::endl;
else
std::cout << "not a function" << std::endl;
}
void print(){}
int main()
{
f1(print);
f2(print);
return 0;
}
根据 f1,print 不是函数。
根据f2,print是一个函数。
理解为什么会这样有助于理解 && 运算符
【问题讨论】:
-
函数参数中的
&和&&运算符是非 逻辑AND - 它们分别是引用运算符和r-value reference operator。 -
@AdrianMole 他们根本不是操作员。
-
@HolyBlackCat 公平点。编辑我的评论为时已晚,但我认为我提供的链接应该是(新的)欺骗目标。
-
@Vince 检查this。要了解为什么在第一种情况下
T会变成void (&)(),请阅读转发引用(T&&是其中之一)。
标签: c++ pass-by-reference function-pointers rvalue