如何重载结构体的空操作符?

3

我希望重载一个函数来检查结构体对象是否为空。

这是我的结构体定义:

struct Bit128 {
    unsigned __int64 H64;
    unsigned __int64 L64;

    bool operate(what should be here?)(const Bit128 other) {
        return H64 > 0 || L64 > 0;
    }
}

这是测试代码:

Bit128 bit128;
bit128.H64 = 0;
bit128.L64 = 0;
if (bit128)
    // error
bit128.L64 = 1
if (!bit128)
    // error

2
查找 operator bool()。作为一个不带参数的成员函数。 - Peter
2
[c]中的结构体没有方法,或者说,请从现在开始标记您的问题,谢谢。 - Antti Haapala -- Слава Україні
4个回答

4
你想要重载 bool 运算符:
explicit operator bool() const {
 // ...

这个运算符不一定必须是,但应该是一个const方法。


为什么要使用explicit,如果OP的用例需要隐式转换呢? - AndyG
1
@AndyG 因为 explicit operator bool 可以在可以上下文转换为bool的地方使用。这仍然比隐式转换更加严格,因此应该是声明 operator bool 的默认方式。 - zett42
@zett42:我明白了。谢谢! - AndyG

4
#include <cstdint>
struct Bit128 
{
    std::uint64_t H64;
    std::uint64_t L64;
    explicit operator bool () const {
        return H64 > 0u || L64 > 0u;
    }
};

除非 OP 没有可用的 C++11,否则应该使用 explicit operator bool(),否则应该使用“安全布尔”惯用语,例如其中一个 boost 实现 - zett42
@zett42:是的,这样会更安全。 - Pixelchemist

2
您要查找的语法是 explicit operator bool() const,这在 c++11 及更高版本中是安全的

2

虽然没有“empty”运算符,但如果你希望对象在布尔上下文中具有意义(例如if条件语句),你需要重载布尔转换运算符:

explicit operator bool() const {
  return H64 != 0 || L64 != 0;
}

请注意,显式转换运算符需要使用C++11。在此之前,您可以使用非显式运算符,但这会带来许多弊端。相反,您应该搜索安全布尔习惯用法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接