0

I don't understand what does mean typedef void (Testable::*bool_type)() const; applied to operator

Is such code

class Testable {
    typedef void (Testable::*bool_type)() const;

public:

    operator bool_type() const {
     ...
    }
};

equivalent to

class Testable {

public:

    void operator ()() const {
     ...
    }
};

?

Ivan Kush
  • 2,462
  • 2
  • 15
  • 37

1 Answers1

2
class Testable {
    typedef void (Testable::*bool_type)() const;

public:

    operator bool_type() const {
     ...
    }
};

… defines an implicit conversion to bool_type, which is an innaccessible pointer to member type.

This is a C++03 technique to provide implicit conversion to bool while avoiding unintended implicit conversions, in particular for function call overload resolution. The returned member pointer converts to bool but not to any type that could conceivably be used for a function argument. In contrast, a pure bool result would convert to e.g. int, and a void* result, as used by C++03 iostreams, would match a void* formal argument.

With C++11 and later you would instead use explicit, like this:

explicit operator bool() const { return whatever; }

But better, define a named conversion function, e.g.

auto is_empty() const -> bool { return whatever; }

That was generally better also in C++03. :-)


Regarding “is such code equivalent to…”, no, it's not.

Community
  • 1
  • 1
Cheers and hth. - Alf
  • 135,616
  • 15
  • 192
  • 304