5

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?

nikitablack
  • 4,359
  • 2
  • 35
  • 68
  • 4
    I don't see why you would expect anything different here. The `float` in `S` is the *first* type parameter `T1`, not the second `T2`. But the specialization is for if `T2` is `float`. – 5gon12eder Feb 26 '16 at 12:52
  • @5gon12eder Presumably, the OP is attempting to specify the template parameter of the partial specialization (`T`); not an uncommon beginner mistake. – T.C. Feb 26 '16 at 12:58
  • My initial thoughts were that id I specify one template parameter, compiler should select specialization, because it prefer specialization over base. – nikitablack Feb 26 '16 at 13:18

1 Answers1

10

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)
Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157