c++ - 重载的按位或运算符 ('|' ) 是否具有明确定义的评估顺序?

标签 c++ operator-overloading language-lawyer bitwise-or

如果我的 C++ 类重载了按位或运算符 (|),C++ 语言规范是否保证传递给该运算符的一系列调用的参数将从左到右求值正确的?还是评估顺序实现已定义(或未定义)?

(IIRC C++ 的内置 | 运算符具有实现定义的求值顺序;但当运算符已为类重载时,情况可能有所不同?)

下面是一个程序,它举例说明了我要问的问题:这个程序是否保证打印出 0 1 2 3 4(就像我目前坐在的 Mac 上一样),或者它可以在某些环境中合法地打印出 4 3 2 1 0(或其他一些顺序)吗?

#include <iostream>

class mytype_t
{
public:
   mytype_t(int v) : _val(v) {/* empty */}

   mytype_t operator | (const mytype_t & rhs) const {return (_val | rhs._val);}

private:
   int _val;
};

mytype_t func(int v)
{
   std::cout << v << std::endl;
   return mytype_t(v);
}

int main(int, char **)
{
   mytype_t x = func(0) | func(1) | func(2) | func(3) | func(4);
   return 0;
}

最佳答案

如果内置运算符规定了特定的顺序,则参数也会以与重载相同的顺序求值。这是相关段落(来自 n4659,C++17 草案),强调我的:

[over.match.oper]

2 If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 12 (where @ denotes one of the operators covered in the specified subclause). However, the operands are sequenced in the order prescribed for the built-in operator (Clause [expr]).

所以不,重载的 operator| 将没有明确定义的求值顺序,因为内置的没有。

关于c++ - 重载的按位或运算符 ('|' ) 是否具有明确定义的评估顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513909/

相关文章:

c++ - 如何在 Linux 上使用 Qt 读取 HID 设备 (/dev/hidrawX)?

c++ - 源文件中的非类型模板参数显式实例化

c++ - 将一个对象与左侧的常数相乘

c++ - 无法在 C++ 中定义++ 运算符,这里有什么问题?

swift - Swift 中的泛型运算符重载

c++ - 为什么 C++ 模板接受数组并不比一个接受指针 (bis) 更专业?

c++ - 使用用户定义的转换运算符的函数模板重载决议

c++ - 仅在我的 2d 引擎中集成 Box2D 碰撞检测?

c++ - 对非常量对象的 constexpr 引用

c++ - 有条件包含 : integral constant expression is unlimited?