【发布时间】:2021-01-20 07:43:24
【问题描述】:
给定 C++ 参考折叠规则的几个来源如下:
A& & becomes A&
A& && becomes A&
A&& & becomes A&
A&& && becomes A&&
(例如http://thbecker.net/articles/rvalue_references/section_08.html)
我可以举一个例子让A&&&变成A&
template <class T> void f1(T&& param) {
// T t = 5; // does not compile because T is T&
param++; // param collapses from int&&&& to int&&
}
void demo()
{
int x = 8;
int &y = x;
f1(y); // OK T will still be int&, param will go to int&&& -> collapses to int&
cout << y; // prints 9
}
我希望 A&& && 变成 A&& 的类似内容,但是当我使用 RValue 调用时,T 被推导出为 int,因此这并没有显示我想要的结果。
template <class T> void f1(T&& param) {
T t = 5; // compiles since T is int
T t2 = t; // would not compile if T was int&&
t2++;
cout << t; // prints 5 since t2 was not a reference
}
void demo()
{
f1(8); // OK T deduced to int, param will go to int&& , no collapsing
}
谁能帮我展示一个类似的例子,将 T 推导出为 T&& 并将参数从 T&&&& 折叠为 T&&?
【问题讨论】:
-
你可以叫它
f1<int&&>(8);。 -
考虑,例如,
f1<decltype(xvalue)>(...));。这里,T将是some_type&&,param的类型将从some_type&& &&折叠到some_type&&。
标签: c++ templates forwarding-reference