返回类型取决于算术运算的顺序.对吗?
Return type depending on the order in arithmetic operation. Is it correct?
考虑以下代码片段:
template <typename U>
struct Un {
Un (int p) : n {p} {}
U operator+ (U v) const {
return U {n + v.n};
}
int n {};
};
struct R : Un<R> {
using Un::Un;
};
struct D : Un<D> {
using Un::Un;
D (R v) : Un {v.n} {}
operator R () const {
return n;
}
};
的用法如下:
template <typename T>
void what_type (T t) {
std::cout << "type R = " << std::is_same<T, R>::value << std::endl;
std::cout << "type D = " << std::is_same<T, D>::value << std::endl;
}
R r {10};
D d {10};
what_type (r+d);
what_type (d+r);
输出是:
type R = 1
type D = 0
type R = 0
type D = 1
表示在算术表达式中,如果R
类型出现在第一个,则整个表达式为R
类型,如果D
类型出现在第一个,则表达式为D
类型。
所以,我的理解是这样的:
在r+d
中,我们首先创建R
类型的对象,然后创建D
类型的对象,由于D
实现了operator R()
,因此将D
对象转换为R
,实际上得到r+r
。在d+r
中,我们首先创建了D
类型的对象,然后是R
类型的对象,因为D
有一个构造函数,它接受R
对象,它从之前创建的r
中创建了D
对象,这实际上给了我们d+d
。
我的理解正确吗?或者对于这种情况还有其他规则吗?
你的理解有缺陷。您将二进制operator+
定义为成员函数。这意味着作业的左边是固定不变的。对于D
和R
,分别是D
和R
。
d+r
本质上与d.operator+(r)
相同,对于Un<D>
返回D
。对于r+d
来说也是一样的。
在这两个表达式中都"创建"左操作数。
返回类型取决于算术运算的顺序。它是正确吗?
只有在涉及重载操作符时才能为真。对于内置操作符,参数的顺序不影响表达式的类型。
对于重载操作符,表达式的类型取决于重载解析的结果。
考虑一个更简单的例子,操作符被全局重载:struct A { operator int() const; };
struct B { operator int() const; };
A operator+(A, int);
B operator+(B, int);
A a;
B b;
a + b // resolved as a + (int)b; the type of the expression is A
b + a // resolved as b + (int)a; the type of the expression is B
请注意,如果没有定义B operator+(B, int);
, b + a
仍然会被解析,但现在是(int)a + (int)b
,因此它的类型将是int
。
相关文章:
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- C++ C++17 中的序列点和对评估顺序的更改
- 多线程应用程序,我做得对吗
- 下面链接中的声明不需要存储类说明符"static"。我说的对吗?
- 我的公司做得对吗,在前任之间共享数据
- 对定义顺序的向量的子集进行高效排序
- C++ GTK 线程.我做得对吗
- 使用g++编译多个.cpp和.h文件.我做得对吗
- "incompatible types in assignment of 'char' to 'char'[100]"我使用的是 strcat 对吗?
- 基准代码——我做得对吗
- AES CTR模式-加密用Crypto++解密-我做得对吗
- 测试答案是错的,对吗?它不会崩溃,因为我们删除NULL指针,这是安全的
- 提升启用/disable_if功能对的顺序重要吗?
- 学习c++矢量.我这样做对吗?可以简化对vector::push_back()的重复调用吗?
- 返回类型取决于算术运算的顺序.对吗?
- 我可以从智能卡的密钥容器中获得公钥/私钥对吗?
- 第一次用智能指针,我做得对吗?
- c++线程速度测试,我做得对吗?
- 使用读/写STL字符串.对吗?
- C++2D长方体碰撞,对吗