2019-11-07

Using enum

C++20にはusing enumが入る。この機能、すっかり見逃していた。

どのような機能かというと、scoped enumを名前空間のusing directiveのように使うことができる。

using enumがないと以下のように書かなければならないが


enum struct color { red, green, blue } ;

void f( color c )
{
    switch( c )
    {
        case color::red :
            break ;
        case color::green :
            break ;
        case color::blue :
            break ;
    }
}

using enumを使えば以下のように書ける。


enum struct color { red, green, blue } ;

void f( color c )
{
    using enum color ;
    switch( c )
    {
        case red :
            break ;
        case green :
            break ;
        case blue :
            break ;
    }
}

scoped enumは暗黙の型変換をしないので、従来のenumに変わって使われるべきだが、いちいちenum名を修飾子なければならないのは面倒だ。そこで、名前空間のusingディレクティブのような機能、using enumが追加された。

3 comments:

You can use some HTML elements, such as <b>, <i>, <a>, also, some characters need to be entity referenced such as <, > and & Your comment may need to be confirmed by blog author. Your comment will be published under GFDL 1.3 or later license with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.