Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template member default initialization

Suppose I have got the following template

template <typename T>
class{
   T t;
};

Now, I want to add a constructor that initializes t with the default value for its type. That is, for numerical types, t should be initialized with 0, for pointers, t should be initialized with nullptr. Finally, there could be other types like structs. Here, a good initialization would be the default constructor (which is invoked anyway, so I do not have to do anything here).

In conlusion I am looking for something like this:

template<typename T>
class X{
    T t;
    X() : t(default_value<T>::value);
}

As my imaginary syntax points out, I think it could be possible with some kind of template with different specializations which carry the default values. But how to handles structs and classes? Since I have specified t(...), the default constructor is no longer an option.

like image 265
gexicide Avatar asked Dec 16 '22 19:12

gexicide


1 Answers

You can just do

X() : t() { }

And/or this in C++11

X() : t { } { } // see Johannes Schaub's comments about this

That will value initialise (or is it default initialisation?) t to whatever the default value is for its type, be it 0 for built-in's, a series of (value?default) initialisations for arrays, or using the default constructor for user-defined types.

like image 132
Seth Carnegie Avatar answered Dec 29 '22 10:12

Seth Carnegie