根据条件真假,返回对应类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template<bool value, typename T1, typename T2>
struct ConditionT {};
template<typename T1, typename T2>
struct ConditionT<true, T1, T2>
{
typedef T1 typeT;
};
template<typename T1, typename T2>
struct ConditionT<false, T1, T2>
{
typedef T2 typeT;
};

void test()
{
typename ConditionT<true, int ,float>::typeT type_T;
static_assert(std::is_same_v<decltype(type_T), int>, "type_T is not int");
// 静态断言失败
// static_assert 的第二个参数会作为错误信息或原因返回
// "静态断言失败,原因是“typename ConditionT::typeT is not int”"
static_assert(std::is_same_v<typename ConditionT<false, int, float>::typeT, int>, "typename ConditionT::typeT is not int");
}