Hi folks,
I've just figured out something interesting by accident. For demonstration purposes, let's assume we have two classes:
Code:
class one {
public:
explicit operator bool() const noexcept
{
std::cout << "one::operator bool" << std::endl;
return {};
}
operator std::size_t() const noexcept
{
std::cout << "one::operator std::size_t" << std::endl;
return {};
}
};
class two {
public:
explicit operator bool() const noexcept
{
std::cout << "two::operator bool" << std::endl;
return {};
}
operator std::size_t() noexcept // note the missing const
{
std::cout << "two::operator std::size_t" << std::endl;
return {};
}
};
The classes are mostly identical, though the conversion operator of the second class for `std::size_t' is non-const (contrary to the one in the first class).
Code:
int main(){
one first;
if (first) {
}
std::size_t i=first;
std::cout << std::endl;
two second;
if (second) {
}
std::size_t j=second;
}
Running the program above prints this in the terminal:
Code:
one::operator bool
one::operator std::size_t
two::operator std::size_t
two::operator std::size_t
As you can see, making a conversion operator non-const changes the result of certain expressions in a boolean context.
So my questions are:
- Why does the compiler prefer to call operator `std::size_t' and then convert it to a boolean value in the second class?
- What has the use of `const' to do with any of this?
- What would a class with behaviour equal to class `one' but with a non-const operator `std::size_t' look like?
Thanks!