如何使类定义外的运算符重载优先?
How to make overload of operator outside class definition take precedence?
我定义了以下运算符:
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
可能是明智的做法。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用