Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How partial template specialization chosen?

Please explain me the rules for template specialization selection. I have an example:

template<typename T1, typename T2 = int>
struct S : false_type{};

template<typename T>
struct S<T, float> : true_type{};

cout << boolalpha << S<float>::value;

Why the output is false? And in general, what happens with default template parameter typename T2 = int in specialized classes? Does it introduces some influence?

like image 324
nikitablack Avatar asked Feb 26 '16 12:02

nikitablack


People also ask

Why does the need of template specialization arise?

This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.

What is meant by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What does template <> mean in C++?

What Does Template Mean? A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.

How do you define a template class?

A class template can be declared without being defined by using an elaborated type specifier. For example: template<class L, class T> class Key; This reserves the name as a class template name. All template declarations for a class template must have the same types and number of template arguments.


1 Answers

Choosing a template specialization happens in five steps:

  1. Take the primary template declaration. (<T1, T2 = int> S)
  2. Fill in user-specified template arguments. (T1 <- float)
  3. Function templates only: Deduce additional template arguments.
  4. Use defaults for remaining template arguments. (T2 <- int)
  5. Use the partial ordering algorithm (C++14 14.5.6.2) to choose the best-matching specialization. (<float, int> does not match <T, float>, so ignore the specialization; only possibility left is primary template)
like image 156
Sebastian Redl Avatar answered Sep 17 '22 22:09

Sebastian Redl