简体   繁体   中英

C++ Method with an enum class type

A problem occurred when trying to print out a class method which has en enum class type.

I have a method, which returns an enum which is casted to bool:

bool Window::IsVSync() const
{
    return static_cast<bool>(m_WindowData.VSync);
}

m_WindowData.VSync is VSync type.

And that's the enum class:

enum class VSync : bool
{
    Disable = false,
    Enable = true
}

I know that with enum class I don't get an implicit conversion, and that's the reason I cast to bool. And like that everything is working just fine. But with the fact that my enum class is extended from bool in mind, can I do something like this:

VSync Window::IsVSync() const
{
    return m_WindowData.VSync;
}

At first, I thought I could, since we extend the enum class from bool, but I was wrong, and It gives me this error when I try to print to the console:

binary '<<': no operator found which takes a right-hand operand of type 'VSync' (or there is no acceptable conversion)

I print the method to the console with:

std::cout << myWindow.IsVSync() << "\n";

Which is of course, supposed to return either 1 or 0;

When I cast it to bool in the output like that:

std::cout << static_cast<bool>(myWindow.IsVSync()) << "\n";

it works just fine, but I do not want to make the user have to cast it to bool for it to work. I need a solution which is in the method itself, so the calling stays like that

std::cout << myWindow.IsVSync() << "\n";

You can define a stream operator overload outside of the class for the enum type like so:

static std::ostream& operator<<(std::ostream& os, const VSync& val)
{
    switch (val) {
        case VSync::Disable:
            os << "VSync disabled";
            break;
        case VSync::Enable:
            os << "VSync enabled";
            break;
    }
    return os;
}

In this way you don't need to cast anything and can print something more detailed than a 1 or 0 (or having to use std::boolalpha ).

I hope that can help.

It is not extended from bool, is uses the same amount of space as a bool.
With enum, colon does not denote inheritance.

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