Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly initialize member variable of template type?

Tags:

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 image 871
Christian Ammer Avatar asked Jan 26 '10 22:01

Christian Ammer


People also ask

How do you declare a template variable in C++?

A variable template may be introduced by a template declaration at namespace scope, where variable-declaration declares a variable. When used at class scope, variable template declares a static data member template.

What is template typename C++?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

How a template is declared?

A class template must be declared before any instantiation of a corresponding template class. A class template definition can only appear once in any single translation unit. A class template must be defined before any use of a template class that requires the size of the class or refers to members of the class.

How does template work C++?

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.


2 Answers

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).

like image 168
GManNickG Avatar answered Oct 18 '22 17:10

GManNickG


Class template field in C++11 has the same syntax:

template <class T> class A {   public:     A() {}     A(T v) : val(v) {}   private:     T val{}; }; 
like image 34
xunzhang Avatar answered Oct 18 '22 15:10

xunzhang