Priority Variadic Template Template

Given the following simple struct

 template <typename T> struct A { A(T a) {} template <typename ... Ts> A(T a, Ts ... more) {} }; int main() { A<int> a(1); } 

What is the guarantee that A(T a) will be called instead of the constructor of variational patterns and why?

+5
source share
2 answers

The section in the standard you are looking for is ยง14.8.2.4

If A was converted from a function parameter packet, and P is not a parameter packet, then type output is output. Otherwise, using the resulting types P and A, the deduction is then performed as described in 14.8.2.5. If P is a function parameter packet, type A of each remaining parameter type of the argument template parameter is compared to type P of the declarator identifier of the function parameter packet. Each comparison displays the template arguments for subsequent positions in the parameter template packages extended by the parameter package function. If the output for a successful type is specified, the type from the argument template is considered to be at least as specialized as the type from the parameter template.

[Example:

 template<class... Args> void f(Args... args); // #1 template<class T1, class... Args> void f(T1 a1, Args... args); // #2 template<class T1, class T2> void f(T1 a1, T2 a2); // #3 f(); // calls #1 f(1, 2, 3); // calls #2 f(1, 2); // calls #3; non-variadic template #3 is more // specialized than the variadic templates #1 and #2 

- end of example]

+6
source

For the same reason, f(const int&) is a better match than f(const T&) , when T can be inferred as int : A(int) is a function without a template and A(int, Ts...) with Ts... Derived as an empty list is a specialized function.

+2
source

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


All Articles