一般在模板函数中如果定义T&&时,这时候的变量参数不一定专指右值引用的意思,而是万能引用的意思,如下代码所示:
#include <iostream>
#include <boost/type_index.hpp>
template<typename T>
void TestFunc(T&& arg)
{
std::cout << "type of T is " << boost::typeindex::type_id_with_cvr<T>().pretty_name() << ", type of arg is " << boost::typeindex::type_id_with_cvr<decltype(arg)>().pretty_name() << std::endl;
}
int main()
{
int x = 100;
int& lref = x;
TestFunc(x);
TestFunc(100);
TestFunc(std::move(x));
TestFunc(lref);
return 0;
}
输出结果:
type of T is int&, type of arg is int&
type of T is int, type of arg is int&&
type of T is int, type of arg is int&&
type of T is int&, type of arg is int&
可以看到在不同的类型的输入情况下T&&的参数类型被推导出了左引用和右引用。
网友评论