Search code examples
c++classtemplatesconstructorinitialization-list

Initialization list template variable


I tried to look for this on the site but i can't find exactly what I need.
Basically I need to know what is the correct way of initialize a template variable in the default constructor.
Eg.:

template<typename T>
class myClass{
   T *arr;        // no problem with this.
   int size;
   int capacity;
   T def_value;   // how do I initialize this template variable in the constructor?

I tried something like:

myClass(): arr(0), size(0), capacity(0), def_value(0){};

But it doesn't compile because I can't assign 0 to, for example, a char (and I know that). How am I supposed to initialize the def_value correctly?


Solution

  • How am I supposed to initialize the def_value correctly?

    Simply like e.g. this:

    myClass(): arr(nullptr), size(0), capacity(0), def_value() {};
                                                // ^^^^^^^^^^^
    

    or this:

    myClass(): arr(nullptr), size(0), capacity(0), def_value{} {};
                                                // ^^^^^^^^^^^