c – How do I correctly initialize a member variable of template type?

I suggest that I have a template function, as follows:

template
void doSomething ()
{
T a; // a is correctly initialized if T is a class with a default constructor
...
};

But If T is a primitive type, the variable a is not initialized. I can write T a(0), but if T is a class, this does not work. Is there a way to initialize the variable in both cases (T == class, T == int,char,bool,…)?

like this:

 T a{};

Before C 11, this is the simplest approximation:

T a = T();

But it needs T to be copyable (although the copy will definitely be deleted).

I suggest that I have a template function, as shown below:

< p>

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

But if T is a primitive type, the variable a is not initialized. I can write T a(0), but if T is a class, this does not Works. Is there a way to initialize variables in both cases (T == class, T == int, char, bool,…)?

Like this:

T a{};

Before C 11, this is the simplest approximation:

T a = T();

But it requires T to be reproducible (although the copy will definitely Deleted).

Leave a Comment

Your email address will not be published.