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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With