partial template specialisation
Nov 20, 2013 at 4:55pm UTC
Hi there,
I am trying to partially specialise a template with a fixed param, while keeping the other variables. Right now I am hitting a compiler error when trying to partially specialise the template:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
class A{ };
class B{ };
template <typename T1, typename T2>
void foo1(T1 t1, T2 t2){
cout << "Not specialised" << endl;
}
template <typename T1>
void foo1<B>(T1 t1, B t2){ // ERROR: template-id ‘foo1<B>’ in declaration of primary template
cout << "Specialised for the 2nd argument" << endl;
}
template <>
void foo1<B,B>(B t1, B t2){
cout << "Totally specialised" << endl;
}
int main(int argc, char * argv[]) {
A a;
B b;
foo1<A,A>(a, a); // Not specialised
foo1<A,B>(a, b); // Specialised for the 2nd argument
foo1<B,B>(b, b); // Totally specialised
return 0;
}
What is the correct syntax in this case?
Kind regards,
Dean
Nov 20, 2013 at 5:00pm UTC
clang gives a more explicit diagnostic:
test.cc:13:6: error: function template partial specialization is not allowed
void foo1<B>(T1 t1, B t2){ // ERROR: template-id foo1<B> in declaration...
^ ~~~
function templates can be either fully specialized or overloaded, not partially-specialized.
Nov 20, 2013 at 5:02pm UTC
shouldn't line 10 be <B,T1>?
*edit
or <T1,B> rather since t1 is your first template. after thinking about it I dont think you can:
error: function template partial specialization ‘test<b, T1>’ is not allowed
void test<b,T1>( T1 t1 , b t2 )
**edit looks like cubbi beat me
Last edited on Nov 20, 2013 at 5:05pm UTC
Nov 20, 2013 at 5:10pm UTC
Function templates can't be partially specialized; but they overload, and we can use overloading instead.
Function templates can be fully specialized; but even here, we should prefer overloading over specialization.
See
http://www.cplusplus.com/forum/beginner/100227/
Nov 20, 2013 at 6:06pm UTC
To give an example of how you could achieve what I think was the goal ("a fixed param, while keeping the other variables."),
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
template <typename T1, typename T2>
void foo1(T1 t1, T2 t2) {
std::cout << "Not specialised\n" ;
}
template <typename T1>
void foo1(T1 t1, B t2) {
std::cout << "first parameter varies, second parameter fixed\n" ;
}
void foo1(B t1, B t2) {
std::cout << "both parameters fixed\n" ;
}
int main() {
A a;
B b;
foo1(a, a);
foo1(a, b);
foo1(b, b);
}
Nov 27, 2013 at 1:01pm UTC
ok, thanks everybody for the replies.
Kind regards,
Dean
Topic archived. No new replies allowed.