有时候需要根据条件进行类型定义,比如下面这种情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct test_struct
{
char c;
int i;
};

struct test_struct_2
{
char c;
double d;
};

if (flag)
typedef bb::test_struct AAA;
else
typedef bb::test_struct_2 AAA;

AAA a;

编译会报错 error: ‘AAA’ was not declared in this scope。

这个时候就可以用std::conditional来做, 有两种方式:

1
2
3
4
5
6
#include <type_traits>

using AAA = typename std::conditional<
flag == true,
bb::test_struct,
bb::test_struct_2 >::type;

or

1
2
3
4
typedef std::conditional<
flag,
bb::test_struct,
bb::test_struct_2 >::type AAA;

获取变量的类型用tpyeid,

1
2
3
#include <typeinfo>

std::cout << typeid(a).name() << std::endl;

参考:https://blog.csdn.net/photon222/article/details/99327989