2

I know specializing function templates is wrong

This question is out of Curiosity.

say I have a function template

template<typename T>
void foo(T){}

and I specialize it

template<>
void foo(std::initializer_list<int>){}

and I call this like

foo({1, 2, 3});

I get an error "no instance of foo matching brac-enclosed initializer list" pointing to the primary template (overloading works fine as expected)

but if I change the function base template to taking initializer_list as parameter everything is ok.

what exactly is happening?

compiler : gcc 4.8.2 helpful link

Community
  • 1
  • 1
Koushik Shetty
  • 2,146
  • 4
  • 20
  • 31
  • @Casey oh i dint realise that. thanks. – Koushik Shetty Jan 22 '14 at 15:22
  • 2
    Actually compilers are perfectly allowed to do that if you pass in an actual `std::initializer_list` object. They are forbidden to deduce `initializer_list` (or anything else) from the syntactic initializer list. Basically, passing `{ whatever }` to a `f(T)` doesn't work. – Sebastian Redl Jan 22 '14 at 15:59
  • @SebastianRedl ah understood. but dint realise that because i was thinking that the specialization will catch this list. i knew explicitly qualifying will work but dint understand this point. basically `{ whatever}` doesnt work even for aggregate and POD types when it comes to deduction right? – Koushik Shetty Jan 22 '14 at 16:12
  • Specializations are taken into account _after_ overload resolution picks the base template. – Xeo Jan 22 '14 at 16:38
  • @Xeo does this go for overloads too? i mean are the overloads are matched first ? – Koushik Shetty Jan 22 '14 at 16:41
  • Yes. Overload resolution picks the best matching function, and if that's a template, checks for specializations. – Xeo Jan 22 '14 at 16:52

0 Answers0