Initializing C ++ Template Constructor

template<class T> class Node { public: Node(Node<T>* next=NULL, T data=T()) : _next(next), _data(data) { } Node<T>* _next; T _data; }; 

I am new to C ++ template. For the default parameters, T data = T() standard way to do this? Maybe T data = 0 is ok too?

+4
source share
2 answers

This is not "constructor initialization", this is the default parameter. It allows the caller to provide fewer arguments than the function; undefined arguments will default.

Another way to do this:

 template<class T> class Node { public: Node(Node<T>* next, T data) : m_next(next), m_data(data) {} Node(Node<T>* next) : m_next(next), m_data() {} Node(void) : m_next(NULL), m_data() {} Node<T>* m_next; T m_data; }; 

In the case where less than two arguments are allowed, but calls different constructors (which have almost the same behavior).

There are several advantages to using separate overloads:

  • No copy constructor is required if the data parameter is always omitted.
  • The default constructor is not required if the data parameter is always specified.
+6
source

This has nothing to do with constructors; what you see is a combination of default function arguments and value initialization.

The latter is described in the C ++ 03 standard, ยง8.5 / 5:

To initialize an object of type type T means:

  • if T is a class type (section 9) with a constructor declared by the user (12.1), then the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);
  • if T is the type of a non-unit class without a constructor declared by the user, then each non-static data element and components of the base class T are initialized with a value;
  • if T is an array type, then each element is initialized with a value;
  • otherwise the object is initialized to zero

and

For zero initialization of an object of type T means:

  • if T is a scalar type (3.9), the object is set to 0 (zero), converted to T;
  • if T is a type of non-unit class, each non-static data member and each subobject of the base class are initialized to zero;
  • if T is a union type, objects first named data member89) are initialized to zero;
  • if T is an array type, each element is initialized to zero;
  • if T is a reference type, initialization is not performed.

And finally, combining it, ยง8.5 / 7:

An object whose initializer is an empty set of brackets, i.e. (), must be initialized with a value.

+3
source

Source: https://habr.com/ru/post/1346840/


All Articles