操作符+()选择右值引用变量而不是const左值变量

operator+() choose rvalue reference variation instead of const lvalue variation

本文关键字:变量 const 引用 选择 操作符      更新时间:2023-10-16

我试图理解在下面的代码中发生了什么。它只是2个std::array的加法,我假设输出是:

C1 = const C1&+ const C2&

而不是:

C1&和;= C1&和;+ C2&,

显然,ararr不是临时的。

这里出了什么问题,我该如何解决?

#include <iostream>
#include <array>
using namespace std;
template<typename C1, typename C2>
C1//inline typename std::enable_if<is_densevector<C1>::value && is_densevector<C2>::value, C1>::type
operator+(const C1 &v1, const C2 &v2) { cout << "C1 = const C1& + const C2&" << endl; C1 r; return r; }
template<typename C1, typename C2>
C2//typename std::enable_if<is_densevector<C1>::value && is_densevector<C2>::value, C2>::type
&&operator+(const C1 &v1, C2 &&v2) { cout << "C2&& = const C1& + C2&&" << endl; return v2; }
template<typename C1, typename C2>
C1//inline typename std::enable_if<is_densevector<C1>::value && is_densevector<C2>::value, C1>::type
&&operator+(C1 &&v1, const C2 &v2) { cout << "C1&& = C2&& + const C2&" << endl; return v1; }
template<typename C1, typename C2>
C1//inline typename std::enable_if<is_densevector<C1>::value && is_densevector<C2>::value, C1>::type
&&operator+(C1 &&v1, C2 &&v2) { cout << "C1&& = C1&& + C2&&" << endl; return v1; }
int main()
{
    std::array<double,3> ar{1,2,3}, arr{3,2,1};
    ar + arr;
    return 0;
}

&&当用于模板参数时,如果参数是左值,则将折叠为&,因此最后一个定义变为

template<typename C1, typename C2>
C1& operator+(C1& v1, C2& v2);

编译器会优先选择

template<typename C1, typename C2>
C1 operator+(const C1 &v1, const C2 &v2)

(或任何其他),因为您的数组不是const