Ada subtype equivalent in C++

前端 未结 5 2085
悲&欢浪女
悲&欢浪女 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:51

    What you want might (at least partially) be realized using std::variant introduced with C++17.

    struct Monday {};
    struct Tuesday {};
    /* ... etc. */
    using WeekDay= std::variant;
    

    The following code defines sub_variant_t which constructs a new variant from the submitted type. E.g. using Working_Day= sub_variant_t; takes the first five elements from Weekday.

    template
    struct sub_variant_h;
    
    template
    struct sub_variant_h >
    {
        using type= std::variant... >;
    };
    
    template
    struct sub_variant
    {
        using type= typename sub_variant_h >:type;
    };
    
    template
    using sub_variant_t = typename sub_variant::type;
    

    If you want to copy values from the smaller type (Working_Day) to the larger one (Weekday) you can use WeekDay d3= var2var( d1 ); where var2var is defined as follows.

    template
    toT
    var2var( std::variant const & v )
    {
        return std::visit([](auto&& arg) -> toT {return toT(arg);}, v);
    }
    

    See this livedemo.

提交回复
热议问题