简体   繁体   中英

C++11: Regular enums, namespaces, and type safety

With enum class in C++11 you can't assign an enum to an int without casting. With regular enum in C++11, is it correct that it's not type safe and that you can accidentally assign to an int?

What I had hoped to do was bundle helper functions in a namespace with the enum:

namespace color {
    enum Color { white, black, none };
    Color opposite (Color c);
    Color is_valid (Color c);
    // etc...
}

In that case, I already have the namespace protection with color::white , but I do not believe this is typesafe. Is there a way to do it without being overly verbose, ie color::Color::white with an enum class ?

instead of a namespace, what about a class? ( live here )

#include <iostream>

class color {
public:
    enum internal_color { red, green, blue };
    color(internal_color c_): c(c_) {}
    operator internal_color() { return c; }
    color opposite() { return color(internal_color(blue - c)); }
    static bool invalid_color(int i) { return i < red || i > blue; }
    static color validated_color(int i) { if( invalid_color(i) ) throw "blblb"; return color(internal_color(i)); }
private:
    internal_color c;
};

int main() {
    color c(color::red);
    std::cout << c << std::endl;
    auto d = color::validated_color(1);
    std::cout << d << std::endl;
    auto x = c.opposite();
    std::cout << x << std::endl;
    auto e = color::invalid_color(3);
    std::cout << e << std::endl;
/*
    color f(5); // does not compile in c++11
    std::cout << f << std::endl;
*/
}    

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