Does C++ offer something similar to Ada\'s subtype
to narrow a type?
E.g.:
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday,
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
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.