Ada subtype equivalent in C++

前端 未结 5 2087
悲&欢浪女
悲&欢浪女 2021-02-12 22:39

Does C++ offer something similar to Ada\'s subtype to narrow a type?

E.g.:

type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday,          


        
5条回答
  •  礼貌的吻别
    2021-02-12 22:56

    No, not natively.

    What you describe might be best represented as a scoped enum, accompanied by a separate scoped enum with a subset of enumerations who share numerical representations with the "parent" scoped enum.

    You could further define some conversions between the two, but without reflection it's not really possible to make it all elegant and intuitive, at least not without hardcoding and duplicating loads of stuff which rather defeats the purpose.

    It would be best, when programming C++, to attempt entirely abandoning the mindset imbued by programming in other languages.

    That being said, this is actually quite a nice feature idea, though I wouldn't hold my breath!

    Workaround: just use an enum, and apply range checking where you need to.

提交回复
热议问题