Can a class template be created without members?

The Wikipedia article says the following:

Creating an instance of a class template does not lead to the creation of its element definitions.

I can’t imagine that any class in C ++ was created, whether from a template or not, where class instances were not created either?

+6
source share
3 answers

Many early C ++ compilers created instances of all member functions, regardless of whether you called them or not.

Consider, for example, std::list , which has a member function called sort . With the current, properly functioning compiler, you can create a list instance of a type that does not support comparison. If you try to use list::sort , it will fail because you do not support comparison. Until you call sort on this list, all this is fine, because list<T>::sort will not be created unless you name it.

Together with those older, poorly functioning compilers, trying to create a list<T> meant that list<T>::sort was created even if you had never used it. The existence of list::sort meant that you had to implement < for T , just to create list<T> , even if you had never used sort in a list of this type at all.

+9
source

The standard clearly states that (both non-template and template) member methods should only be created when used.

Excerpt from the C ++ standard (N3690 - 14.7.1 (2) Implicit implementation)

2 If a member of a class template or a member template is not explicitly created or is not explicitly specialized, the specialization of a member is implicitly created when the specialization is referenced in a context requiring a member definition ; in particular, initialization (and any side effects associated with it) of a static data member does not occur if the static data member itself is not used in such a way that a definition of the static data member is required.

+1
source

Class methods are also members. Class template methods are created when they are called for this instance of the class. Therefore, it is possible that these member methods are never created.

0
source

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


All Articles