#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,打印不是函数。
根据 f2,print 是一个函数。
理解为什么会这样有助于理解 && 运算符
最佳答案
在这两种情况下,函数都是通过引用传递的。这两个函数都处理对函数 print 的左值引用。
采用
std::is_function_v<std::remove_reference_t<T>>
代替
std::is_function_v<typename std::remove_pointer_t<T>>
您还可以在这两个函数中插入这样的语句
std::cout << std::is_lvalue_reference_v<decltype( t )> << '\n';
确保函数处理对 rpint 的左值引用。
考虑到您需要包含标题
<type_traits>
.如果您希望函数处理函数指针,那么您需要使用这样的调用
f1(&print);
在这种情况下,第二个函数应该声明为
template<typename T>
void f2( const T& t);
否则,您可能无法将非常量引用绑定(bind)到右值。
或者如果您不想使用限定符 const,则调用函数 f2。
auto p = print;
f2(p);
关于c++ r值引用应用于函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366121/