简体   繁体   中英

Error about deleted bool operator when static_cast to int

When doing a static_cast<int> , I'm getting a complaint about a deleted bool() operator:

main.cpp:15:35: error: use of deleted function 'J::operator bool()'
     j = static_cast<int>(*this) + 1;
                               ^

Probably something obvious I'm missing here, but I don't see why it would be trying to run the bool conversion:

#include <iostream>

struct J {
    int j;
    J (int j) : j (j) {}

    operator bool() = delete;

    explicit operator int() const {
        if (j > 304) { std::cout << "Out of range\n"; }
        return j;
    }

    J& operator++ () {
        j = static_cast<int>(*this) + 1;
        return *this;
    }
};

int main() {
    J b {1020};
    ++b;
}

In short, changing the bool operator overloads to either one of these:

explicit operator bool() = delete; // Prevent implicit conversion (int to bool)
operator bool() const = delete;    // Non-const had higher priority for resolution

This is about two things. Implicit integer conversion and function resolution order.


It seems like this is basically of typical C++ function resolution. Let's recall that:

class A {
public:
  void foo() { cout << "non-const" << endl; }
  void foo() const { cout << "const" << endl; }
};

int main() {
  A a1;
  a1.foo(); // prints "non-const"
  const A a2;
  a2.foo(); // prints "const"
  return 0;
}

If non-const one is available, it has higher priority than the const one.

Back to your example, let's make things clear, change the bool cast operator to non-const int cast.

explicit operator int() = delete; // Instead of "operator bool() = delete;"

With this, it still fails for the same reason with above. As operator++ is non-const so this is non-const so static_cast<int>(*this) is resolved to non-const operator int . However it is deleted so the compiler complains. So if we did not have this non-const one deleted, the it would have been resolved with const version and work correctly.

So now what about operator bool() = delete; ? This function is not declared with explicit so int will implicitly try to convert to bool . So it is resolved with the deleted one before getting to the const one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM