临时const数组未绑定到右值引用 [英] Temporary const array not binding to rvalue reference
问题描述
我有以下测试程序:
#include <iostream>
#include <type_traits>
#include <utility>
template<typename Ty, std::size_t N>
void foo(Ty (&&)[N])
{
std::cout << "Ty (&&)[" << N << "]\t" << std::is_const<Ty>::value << '\n';
}
template<typename Ty, std::size_t N>
void foo(Ty (&)[N])
{
std::cout << "Ty (&)[" << N << "]\t" << std::is_const<Ty>::value << '\n';
}
template<typename Ty>
using id = Ty;
int main()
{
std::cout.setf(std::cout.boolalpha);
foo(id<int[]>{1, 2, 3, 4, 5});
foo(id<int const[]>{1, 2, 3, 4, 5}); // <-- HERE.
int xs[]{1, 2, 3, 4, 5};
foo(xs);
int const ys[]{1, 2, 3, 4, 5};
foo(ys);
foo(std::move(xs));
foo(std::move(ys));
}
我希望带有箭头的行会像其上方的非const调用一样调用右值重载,但是不会.
I would expect that the line marked with an arrow would call the rvalue overload like the non-const call just above it but it doesn't.
这仅仅是GCC中的错误,还是标准中有某些导致左值重载被选中?
Is this just a bug in GCC or is there something in the standard that causes the lvalue overload to be selected?
推荐答案
根据标准§12.2 [class.temporary]
:
类类型的临时变量是在各种上下文中创建的:绑定一个 引用prvalue(8.5.3),返回prvalue(6.6.3), 创建prvalue(4.1、5.2.9、5.2.11、5.4)的转换,引发 例外(15.1),输入处理程序(15.3),在某些情况下 初始化(8.5).
Temporaries of class type are created in various contexts: binding a reference to a prvalue (8.5.3), returning a prvalue (6.6.3), a conversion that creates a prvalue (4.1, 5.2.9, 5.2.11, 5.4), throwing an exception (15.1), entering a handler (15.3), and in some initializations (8.5).
所以id<int const[]>{1, 2, 3, 4, 5}
是临时的,因此是prvalue §3.10 [basic.lval]
:
So id<int const[]>{1, 2, 3, 4, 5}
is a temporary and therefore is an prvalue §3.10 [basic.lval]
:
右值(之所以称为历史值,是因为右值可能会出现在 赋值表达式的右侧)是一个xvalue,一个 临时对象(12.2)或其子对象,或者不是 与对象相关联.
An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.
prvalue("pure" rvalue)是不是xvalue的rvalue.
A prvalue ("pure" rvalue) is an rvalue that is not an xvalue.
因此应选择带有右值引用参数的重载函数.
Hence shall be selected overloaded function with rvalue reference argument.
这篇关于临时const数组未绑定到右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!