如何在模板中初始化为零/ NULL [英] How to initialize to zero/NULL in a template

查看:143
本文介绍了如何在模板中初始化为零/ NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写模板时,我想将我的变量初始化为一个值,该值作为零或null数据类型。如果我将它设置为0x00是否将为任何类型的零/ NULL?

While writing a template, I want to initialize my variable to a value that serves as zero or null the the data type. If I set it to 0x00 is it going to serve as zero/NULL for any type ?

例如

这是模板声明

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

现在,如果我定义一个T => std :: string类型的实例, code> NULL ?

Now if I define an instance of type T => std::string the above statement serves as NULL ?

int code> unsigned int 。对于它们都是0?

What about "int" and "unsigned int". For both of the it serves as "0" ?

推荐答案

使用值初始化

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

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




值初始化的效果:

The effects of value initialization are:

1)如果T是至少有一个用户提供的任何类型的构造函数的类类型,则调用默认构造函数;

直到C ++ 11)

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)如果T是没有默认构造函数或者用户提供或删除的默认构造函数的类类型, ;

(自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)如果T是一个非联合类类型,没有任何用户提供的构造函数,静态数据成员和T的基类成分被初始化;

(直到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)如果T是一个具有既不是用户提供也不是删除的默认构造函数的类类型(也就是说,它可以是具有隐式定义或默认默认构造函数的类),该对象是零初始化的,然后如果它是默认初始化的有一个非平凡的默认构造函数;

(自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)如果T是一个数组类型,数组是值初始化的;

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

4)否则,对象是零初始化的。

4) otherwise, the object is zero-initialized.

这篇关于如何在模板中初始化为零/ NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆