Christian Ammer Christian Ammer - 10 months ago 36
C++ Question

How to correctly initialize variable of template type?

suggest i have a template function like following:

template<class T>
void doSomething()
T a; // a is correctly initialized if T is a class with a default constructor

But variable a leaves uninitialized, if T is a primitive type. I can write T a(0), but this doesn't work if T is a class. Is there a way to initialize the variable in both cases (T == class, T == int, char, bool, ...)?


Like so:

T a{};

Pre-C++11, this was the simplest approximation:

T a = T();

But it requires T be copyable (though the copy is certainly going to be elided).