如何使类定义外的运算符重载优先?

How to make overload of operator outside class definition take precedence?

本文关键字:重载 运算符 何使类 定义      更新时间:2023-10-16

我定义了以下运算符:

std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b);
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint32_t b);

当用int调用运算符时,我得到错误:

/misc.hpp:77:12: error: ambiguous overload for ‘operator<<’ (operand types are ‘std::vector<unsigned char>’ and ‘int’)
buffer << first;
~~~~~~~^~~~~~~~
./misc.hpp:62:23: note: candidate: std::vector<unsigned char>& operator<<(std::vector<unsigned char>&, uint8_t)
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b);
^~~~~~~~
./misc.hpp:63:23: note: candidate: std::vector<unsigned char>& operator<<(std::vector<unsigned char>&, uint32_t)
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint32_t b);

我是否可以使uint8_t版本优先,这样我就不需要类型转换,例如,static_cast<uint8_t>调用该运算符?

您可以通过将第二个模板作为模板来破解它:

std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b);
template<class Y>
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, Y b);

重载分辨率将始终优先于非模板函数而不是模板函数,因此此技术引入了足够的层次结构。如果您不希望发出过多的Y类型,请对 Y 类型采用静态断言。

实际上,进一步超载int可能是明智的做法。