问题
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?
回答1:
Choosing a template specialization happens in five steps:
- Take the primary template declaration. (
<T1, T2 = int> S) - Fill in user-specified template arguments. (
T1 <- float) - Function templates only: Deduce additional template arguments.
- Use defaults for remaining template arguments. (
T2 <- int) - 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)
来源:https://stackoverflow.com/questions/35652212/how-partial-template-specialization-chosen