3

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
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
A.J
  • 338
  • 1
  • 4
  • 16

4 Answers4

4

You want to overload the bool operator:

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

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

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Why `explicit` if the OP's use case has an implicit conversion desired? – AndyG Mar 20 '17 at 13:02
  • 1
    @AndyG Because `explicit operator bool` can be used in places where it can be [contextually converted to bool](http://stackoverflow.com/a/39995574/7571258). This is still more restrictive than implicit conversion so it should be the default way of declaring `operator bool`. – zett42 Mar 20 '17 at 13:14
  • @zett42: I see. Thanks! – AndyG Mar 20 '17 at 13:24
4
#include <cstdint>
struct Bit128 
{
    std::uint64_t H64;
    std::uint64_t L64;
    explicit operator bool () const {
        return H64 > 0u || L64 > 0u;
    }
};
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71
  • This should be [`explicit operator bool()`](http://stackoverflow.com/q/6242768/7571258) unless OP doesn't have C++11 available in which case the `safe bool` idiom should be used, e. g. one of these [boost implementations](http://stackoverflow.com/a/11854479/7571258). – zett42 Mar 20 '17 at 19:44
  • @zett42: Would be safer, yes. – Pixelchemist Mar 20 '17 at 20:47
2

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.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
2

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

Community
  • 1
  • 1
Caleth
  • 52,200
  • 2
  • 44
  • 75