如何在模板中初始化为 zero/NULL

How to initialize to zero/NULL in a template

在编写模板时,我想将变量初始化为数据类型为零或空的值。如果我将它设置为 0x00,它会作为任何类型的 zero/NULL 吗?

例如

这是模板声明

template <class T>
...
T A=0x00;

现在,如果我定义类型 T => std::string 的实例,则上述语句用作 NULL ?

int”和“unsigned int”呢?对于两者,它都用作“0”?

您可以使用

T t{};

对于 value initialization

使用Value Initialization:

T A = T(); // before C++11

T A{}; // C++11 and later

The effects of value initialization are:

1) if T is a class type with at least one user-provided constructor of any kind, the default constructor is called;
(until C++11)

1) if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
(since C++11)

2) if T is an non-union class type without any user-provided constructors, every non-static data member and base-class component of T is value-initialized;
(until C++11)

2) if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;
(since C++11)

3) if T is an array type, each element of the array is value-initialized;

4) otherwise, the object is zero-initialized.