简体   繁体   English

C ++ 11:常规枚举,名称空间和类型安全

[英]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. 使用C ++ 11中的enum class ,您不能在不进行强制转换的情况下将enum分配给int。 With regular enum in C++11, is it correct that it's not type safe and that you can accidentally assign to an int? 使用C ++ 11中的常规enum ,它不是类型安全的并且可以意外分配给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. 在那种情况下,我已经有了color::white的名称空间保护,但是我不认为这是类型安全的。 Is there a way to do it without being overly verbose, ie color::Color::white with an enum class ? 有没有一种方法可以做到而又不过于冗长,例如带有enum class color::Color::white

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;
*/
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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