Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overload empty operator of struct?

I want to overload a function to check if a struct object is empty.

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
like image 603
A.J Avatar asked Jan 31 '26 10:01

A.J


2 Answers

#include <cstdint>
struct Bit128 
{
    std::uint64_t H64;
    std::uint64_t L64;
    explicit operator bool () const {
        return H64 > 0u || L64 > 0u;
    }
};
like image 77
Pixelchemist Avatar answered Feb 03 '26 00:02

Pixelchemist


You want to overload the bool operator:

explicit operator bool() const {
 // ...

This operator doesn't have to be, but should be, a const method.

like image 36
Sam Varshavchik Avatar answered Feb 03 '26 00:02

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!