操作符+()选择右值引用变量而不是const左值变量
operator+() choose rvalue reference variation instead of const lvalue variation
我试图理解在下面的代码中发生了什么。它只是2个std::array
的加法,我假设输出是:
C1 = const C1&+ const C2&
而不是:
C1&和;= C1&和;+ C2&,
显然,ar
和arr
不是临时的。
这里出了什么问题,我该如何解决?
#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
。
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 在内存不足之前,我可以声明多少个 const 变量?
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 在类 (C++) 之外设置 const int 成员变量
- 当设置为 const 变量时使用 nullptr
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 既然我们有内联变量,extern const 还有用吗?
- 声明与 const 变量和成员函数相同的标识符
- 无法使用 'const Node *' 类型的右值初始化 'Node *' 类型的变量
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- const_cast const 方法中的"this"将"this"分配给外部变量?
- 如何检查函数是否真的获得了定义为 const 的变量?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 继承,使基本成员变量const
- 是否可以更改函数中成员变量"const"值?
- 在 c++ 中声明一个全局范围变量 const
- 在c++中声明一个局部变量const的好处,如果它的值在编译时不知道