tags:

views:

108

answers:

1

Hi, 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, ...)?

+8  A: 

Like so:

T a = T();
GMan
Thanks, don't know why i didn't remember this.
Christian Ammer
No problem. :].
GMan
just noticed, that something like `int i = bool()` does work aswell... why is this legal ?!... is `bool()` some kind of function in this case ?
smerlin
btw, `unsigned int i = unsigned int();` doesnt compile with GCC, but is it legal ?
smerlin
@smerlin: `bool` and `int` can convert to each other. Also, it should be `unsigned int i = (unsigned int)();`.
GMan
@smerlin: I've answered your first question, and formally asked your second question: http://stackoverflow.com/questions/2144012/explicit-type-conversion-and-multiple-simple-type-specifiers; I believe the answer is that this is not valid for types specified by a combination of simple type specifiers, e.g. `unsigned int`.
James McNellis
`identity<unsigned int>::type()`. Meta-parenthesizer xD
Johannes Schaub - litb