Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Very explicit operator bool

Is the Safe Bool Idiom still useful in C++11 / C++14?


template <typename T, typename Cleanup = QScopedPointerDeleter<T> >
class QScopedPointer
{
    typedef T *QScopedPointer:: *RestrictedBool;
public:
    inline operator RestrictedBool() const
    {
        return isNull() ? Q_NULLPTR : &QScopedPointer::d;
    }

    inline bool isNull() const
    {
        return !d;
    }
protected:
    T *d;
};

QScopedPointer<int> sp;
if (sp) { ... }

struct T {
    operator bool() const { return true; }
};

T t;
if (t) { ... }
do { ... } while (t);
bool ok = t;

T t;
int i = t;
t >> 4;
if (t < 42) { ... }
AnotherClassWithOperatorBool t2;
if (t == t2) { ... }

struct T {
private:
    typedef void (T::*bool_type)() const;
    // or, in C++11:
    // using bool_type = void (T::*)() const;
    void some_unused_function() const;
public:
    operator bool_type() const {
     // return &some_unused_function if true,
     // return nullptr if false
    }
};

struct A {};

struct B {
    explicit B(const A &);
};

void f(const B &);

// it is _not_ possible to implicitly convert a A to B
// because of the explicit constructor. This will fail:
A a;
f(a); // error: implicit conversion requested

struct D {};
struct C {
    operator D() const;
};

void f(const D &);

// since the conversion operator from C to D is implicit,
// it is legal to write:
C c;
f(c); // works: operator D() is implicit

struct D {};
struct C {
    explicit operator D() const;
};

void f(const D &);

C c;
f(c); // error; requires explicit conversion
f(static_cast<D>(c)); // works

struct T {
    explicit operator bool() const { return true; }
};

T t;

bool b1 = t; // fails to compile, implicit conversion

bool b2(t); // works, explicit conversion
bool b3{t}; // works
bool b4 = (bool)t; // works
bool b5 = static_cast<bool>(t); // works

int i = t; // fails to compile
int i(t); // fails to compile
t + 42; // fails to compile

T t;
if (t == 0) { ... }
if (0 == t) { ... }

bool operator==(const T &lhs, std::nullptr_t) { return lhs.isNull(); }
bool operator==(std::nullptr_t, const T &rhs) { return rhs.isNull(); }

struct S {
    T t;
    bool isValid() const { return t; }
};

10 Comments

25 - May - 2016

Arne

struct S {
    T t;
    bool isValid() const { return t?true:false; }
};

25 - May - 2016

Giuseppe D'Angelo

26 - May - 2016

CarelC

26 - May - 2016

Giuseppe D'Angelo

26 - May - 2016

Jon Harper

bool isValid() const { return t != nullptr; }

26 - May - 2016

Jon Harper

26 - May - 2016

Giuseppe D'Angelo

16 - Feb - 2017

Marc Mutz

31 - Jan - 2023

Anonymous(:D)

template <typename T>
operator T(){
    static_assert(false,"conversion to unsupported type not allowed");
}

31 - Jan - 2023

Giuseppe D'Angelo

is_convertible_v<MyType, int>
GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer

Learn Modern C++

Learn more