[英]How can I overload empty operator of struct?
I want to overload a function to check if a struct object is empty. 我想重载一个函数来检查struct对象是否为空。
Here is my struct definition: 这是我的结构定义:
struct Bit128 {
unsigned __int64 H64;
unsigned __int64 L64;
bool operate(what should be here?)(const Bit128 other) {
return H64 > 0 || L64 > 0;
}
}
This is test code: 这是测试代码:
Bit128 bit128;
bit128.H64 = 0;
bit128.L64 = 0;
if (bit128)
// error
bit128.L64 = 1
if (!bit128)
// error
You want to overload the bool
operator: 你想重载
bool
运算符:
explicit operator bool() const {
// ...
This operator doesn't have to be, but should be, a const
method. 此运算符不必是,但应该是
const
方法。
#include <cstdint>
struct Bit128
{
std::uint64_t H64;
std::uint64_t L64;
explicit operator bool () const {
return H64 > 0u || L64 > 0u;
}
};
There's no "empty" operator, but if you want the object to have a significance in boolean contexts (such as if-conditions), you want to overload the boolean conversion operator: 没有“空”运算符,但如果您希望对象在布尔上下文中具有重要性(例如if-conditions),则需要重载布尔转换运算符:
explicit operator bool() const {
return H64 != 0 || L64 != 0;
}
Note that the explicit conversion operator requires C++11. 请注意,显式转换运算符需要C ++ 11。 Before that, you can use a non-explicit operator, but it comes with many downsides.
在此之前,您可以使用非显式运算符,但它有许多缺点。 Instead you'll want to google for the safe-bool idiom.
相反,你会想谷歌的安全布尔成语。
您正在寻找的语法是explicit operator bool() const
, 它在c ++ 11及更高版本中是安全的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.