Baz
Baz

Reputation: 13125

Strange bool overloading

Can you explain for me what the typedef here is doing and what the purpose is?

class C
{
    public:
        ...

        typedef bool (C::*implementation_defined_bool_type)(bool) const;

        operator implementation_defined_bool_type() const {
            return _spi ? &C::isPersistent : 0;
        }

};

Upvotes: 2

Views: 98

Answers (1)

Alok Save
Alok Save

Reputation: 206508

Can you explain for me what the typedef is doing here?

typedef bool (C::*implementation_defined_bool_type)(bool) const;

typedefs a pointer to a const member function of a type C, which takes a bool as input parameter and also returns a bool.

While,

operator implementation_defined_bool_type() const 

Takes in an object of type C and returns a type implementation_defined_bool_type.
It is known as an Conversion Operator.

what is the purpose of it?

It implements the "Safe Bool Idiom", which aims to validate an object in a boolean context.
Note that the Safe Bool Idiom is obsolete with the C++11 Standard.

Good Read:
The Safe Bool Idiom

Upvotes: 5

Related Questions