A.J
A.J

Reputation: 348

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

Upvotes: 3

Views: 1561

Answers (4)

Pixelchemist
Pixelchemist

Reputation: 24936

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

Upvotes: 4

Caleth
Caleth

Reputation: 62576

The syntax you are looking for is explicit operator bool() const which is safe in c++11 and later

Upvotes: 2

Sebastian Redl
Sebastian Redl

Reputation: 71899

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:

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

Note that the explicit conversion operator requires 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.

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

You want to overload the bool operator:

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

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

Upvotes: 4

Related Questions