25

The following template specialization code:

template<typename T1, typename T2>
void spec1()
{

}

Test case 1:

template< typename T1> //compile error
void spec1<int>()
{

}

Test case 2:

template< typename T2> //compile error
void spec1<int>()
{

}

generates the following compilation error:

error C2768: 'spec1' : illegal use of explicit template arguments

Does anyone know why?

cxw
  • 16,685
  • 2
  • 45
  • 81
jameszhao00
  • 7,213
  • 15
  • 62
  • 112

1 Answers1

59

Function templates cannot be partially specialised, only fully, i.e. like that:

template<>
void spec1<char, int>()
{

}

For why function templates cannot be partially specialised, you may want to read this.

When you specialise partially (only possible for classes), you'd have to do it like that:

template <typename T1>
class class1<T1, int>
{

};

so you have to list T1 again.

The way your specialisations are written, they would be ambiguous for spec1<int, int>.

Rüdiger Hanke
  • 6,215
  • 2
  • 38
  • 45
  • 3
    Ah so I can have partially specialized classes embedded with static functions? – jameszhao00 Sep 13 '09 at 01:24
  • Oh, i see the article you link to explains matters already. I removed my answer, since i found that forwarding to a class is more convenient for this case. In cases where `T1` and `T2` are used as types of the function parameters though, i find overloading much more readable, since it is just like normal function overloading then. – Johannes Schaub - litb Sep 13 '09 at 02:18
  • When I read "only possible for classes", I balked. I found that it's possible for both classes and structs ;-). – lmat - Reinstate Monica Apr 17 '14 at 15:26
  • 1
    @LimitedAtonement: As classes and structs are pretty much the same thing, I'm ok with "only for classes". – Mooing Duck Oct 29 '14 at 18:41