Search code examples
c++variable-initialization

How to initialize to zero/NULL in a template


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 ?

for example

This is template declaration

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

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

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


Solution

  • Use 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.