引用折叠 万能引用 std::forward 完美转发
测试
点击查看代码
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <type_traits>
using std::move;
using std::forward;
using std::is_lvalue_reference;
using std::is_rvalue_reference;
using std::is_reference;
template<typename T> void print_type(T&&) { cout << "Rvalue\n"; }
template<typename T> void print_type(T&) { cout << "Lvalue\n"; }
template<typename T> void print_type(const T&) { cout << "Const Lvalue\n"; }
template<typename T>
inline void print_type() {
if (is_lvalue_reference<T>::value)
cout << "is_lvalue_reference\n";
else if (is_rvalue_reference<T>::value)
cout << "is_rvalue_reference\n";
else if (is_reference<T>::value)
cout << "is_reference\n";
else cout << "other type\n";
}
template<typename T>
void test(T&& x) {
cout << "---Test start:\n";
cout << "T:\t";
print_type<T>();
cout << "T&&:\t";
print_type<T&&>();
cout << "x:\t";
print_type(x);
cout << "decltype(x):\t";
print_type<decltype(x)>();
cout << "forward(x):\t";
print_type(forward<T>(x));
cout << "static_cast<decltype(x)>(x):\t";
print_type(static_cast<decltype(x)>(x));
cout << "---Test end.\n" << endl;
}
signed main() {
int x = 114514;
print_type(x);
print_type(move(x));
print_type(1919810);
cout << endl;
test(x);
test(move(x));
return 0;
}
输出
Lvalue
Rvalue
Rvalue
---Test start:
T: is_lvalue_reference
T&&: is_lvalue_reference
x: Lvalue
decltype(x): is_lvalue_reference
forward(x): Lvalue
static_cast<decltype(x)>(x): Lvalue
---Test end.
---Test start:
T: other type
T&&: is_rvalue_reference
x: Lvalue
decltype(x): is_rvalue_reference
forward(x): Rvalue
static_cast<decltype(x)>(x): Rvalue
---Test end.
使用例
点击查看代码
#include <iostream>
using std::cout;
#include <type_traits>
using std::move;
using std::forward;
template<typename T> void print_type(T&&) { cout << "Rvalue\n"; }
template<typename T> void print_type(T&) { cout << "Lvalue\n"; }
template<typename T>
void test(T&& x) {
cout << "\nWith std::forward:\t";
print_type(forward<T>(x));
cout << "Without std::forward:\t";
print_type(x);
}
signed main() {
int x = 114514;
test(x);
test(move(x));
return 0;
}
输出
With std::forward: Lvalue
Without std::forward: Lvalue
With std::forward: Rvalue
Without std::forward: Lvalue
本文来自博客园,作者:Gyan083,转载请注明原文链接:https://www.cnblogs.com/gyan083/p/16387766.html

浙公网安备 33010602011771号