我需要一个
type_chooser
的特质,看起来像
using chosen_type = type_chooser<bool1, T1, bool2, T2, ....., boolN, TN, Telse>;
并且会像
一样工作if (bool1) return T1;
else if (bool2) return T2;
...
else if (boolN) return TN;
else return Telse;
这如何实现(c++20)?
如果它也可以接受偶数个参数,那就太好了,在这种情况下它的工作方式如下:
if (bool1) return T1;
else if (bool2) return T2;
...
else if (boolN) return TN;
else COMPILE_TIME_ERROR;
像这样的混合非类型/类型参数不能用于任意数量的参数。
您可以尝试更改语法。以下是一些选项:
// One argument for the bool and the type
template<bool B, typename T>
struct Case;
template<typename T>
struct Else;
using chosen_type = type_chooser<Case<bool1, T1>, Case<bool2, T2>, ....., Case<boolN, TN>, Else<Telse>>;
// Maybe written as
using chosen_type = first_with_member_type<std::enable_if<bool1, T1>, std::enable_if<bool2, T2>, ..., std::enable_if<boolN, TN>, std::type_identity<TElse>>;
// Type-only arguments
using chosen_type = type_chooser<std::bool_constant<bool1>, T1, std::bool_constant<bool2>, T2, ..., std::bool_constant<boolN, TN>, Telse>;
// Or non-type-only arguments
using chosen_type = type_chooser<bool1, std::type_identity<T1>{}, bool2, std::type_identity<T2>{}, ..., boolN, std::type_identity<TN>{}, std::type_identity<TElse>{}>;
// Move all the bools to a single parameter
using chosen_type = type_chooser<std::integer_sequence<bool,
bool1, bool2, bool3, ..., boolN
>, T1, T2, T3, ..., TN, TElse
>;
// Write out your if/else chain
using chosen_type = decltype([]{
if constexpr (bool1) return std::type_identity<T1>{};
else if constexpr (bool2) return std::type_identity<T2>{};
...
else if constexpr (boolN) return std::type_identity<TN>{};
else return std::type_identity<Telse>{};
})::type;