为什么 const 模板参数不是 universal/forwarding 引用
Why is const template parameter not a universal/forwarding reference
我正在阅读有关通用 [=35=] 参考文献和 this link says 的内容:
此处param
为通用参考:
template<typename T>
void f(T&& param);
但是这里param
不是通用引用,是右值引用:
template<typename T>
void f(const T&& param);
通用引用的定义如下:
If a variable or parameter is declared to have type T&& for some deduced type T, that variable or parameter is a universal reference.
我读到 T 是推导类型,因为 Template argument deduction。
为什么第二种情况不能通用?出于某种原因,const T&& param
的存在是否不遵循模板参数推导?如果是,为什么?
因为它会破坏目的。
即使它是转发引用,在传递右值时你也会得到 const 右值引用。移动语义需要一个 non-const 引用,这样源对象就可以被修改,因为重点是窃取about-to-expire 对象的内部状态,而不是进行可能昂贵的复制。
无论价值类别如何,您都会一直在进行复制。所以在这种情况下“转发”是没有意义的。
前言:官方说法是转发参考
So why is the second case not a universal reference?
因为它是对const 的引用。并且对 const 的引用不是转发引用。
why?
转发引用的全部意义在于,当一个右值作为参数给出时,该参数将被推导为对 non-const 右值的引用,这允许在转发时移动此类参数(同时允许左值不被移动)。您不能从对 const 的引用移动,因为移动构造函数的参数将是对 non-const 的右值引用,它不能绑定到对 const.
的引用
language-lawyer答案是:因为标准是这样说的:
[temp.deduct.call] A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template ...
我正在阅读有关通用 [=35=] 参考文献和 this link says 的内容:
此处param
为通用参考:
template<typename T>
void f(T&& param);
但是这里param
不是通用引用,是右值引用:
template<typename T>
void f(const T&& param);
通用引用的定义如下:
If a variable or parameter is declared to have type T&& for some deduced type T, that variable or parameter is a universal reference.
我读到 T 是推导类型,因为 Template argument deduction。
为什么第二种情况不能通用?出于某种原因,const T&& param
的存在是否不遵循模板参数推导?如果是,为什么?
因为它会破坏目的。
即使它是转发引用,在传递右值时你也会得到 const 右值引用。移动语义需要一个 non-const 引用,这样源对象就可以被修改,因为重点是窃取about-to-expire 对象的内部状态,而不是进行可能昂贵的复制。
无论价值类别如何,您都会一直在进行复制。所以在这种情况下“转发”是没有意义的。
前言:官方说法是转发参考
So why is the second case not a universal reference?
因为它是对const 的引用。并且对 const 的引用不是转发引用。
why?
转发引用的全部意义在于,当一个右值作为参数给出时,该参数将被推导为对 non-const 右值的引用,这允许在转发时移动此类参数(同时允许左值不被移动)。您不能从对 const 的引用移动,因为移动构造函数的参数将是对 non-const 的右值引用,它不能绑定到对 const.
的引用language-lawyer答案是:因为标准是这样说的:
[temp.deduct.call] A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template ...