Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pointer type operator VS const bool operator precedence

#include <cstdint>
#include <iostream>

struct a_struct {
    int64_t* le_int;
    bool not_ok;

    a_struct() : le_int{ new int64_t(0) }, not_ok{ false } {}
    ~a_struct() { delete le_int; }

    operator bool() const {
        return !not_ok;
    }

    operator int64_t* () {
        return le_int;
    }
};

int main(int argc, char** argv) {

    a_struct s;
    s.not_ok = true;
    if (!s)//<-
        std::cout << "o no." << std::endl;

    else if (s.not_ok)
        std::cout << "waddu heck?" << std::endl;

    return 0;
}

In this example the !s resolution prefers the int64_t*() operator over the const bool() operator.

Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since your object s is not const, it prefers the non-const way of calling the type cast operator. So, removing the const from your bool type cast operator does the trick.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading