How to specialize a function template correctly?

D

desktop

I have stumbled upon different ways to declare a function template
specialization.

Are the following examples synonymous or are there significant differences:

template<typename T> // Primary function template
void myTemp(T) {

}


template<> // int version with arg 'a'
void myTemp(int a) {
// do something with a
}


template<> // int type only version
void myTemp(int) {

}


template<> // int int type version
void myTemp<int>(int) {

}
 
Z

Zeppe

desktop said:
I have stumbled upon different ways to declare a function template
specialization.

Are the following examples synonymous or are there significant differences:

template<typename T> // Primary function template
void myTemp(T) {

}


template<> // int version with arg 'a'
void myTemp(int a) {
// do something with a
}


template<> // int type only version
void myTemp(int) {

}

This happens with every function parameter. If you are not going to use
it in the function implementation, you can omit the name of the
parameter, leaving only the type. It's also common practice in order to
avoid warnings referring to the unused variable "a" (if you don't use
it, of course :)).

template<> // int int type version
void myTemp<int>(int) {

}

This is an explicit specialization, while the previous ones are
implicit. The point here is that, as every time in which you can deduce
the template parameters from the function arguments, you don't need to
write them explicitly.

If I can give you a suggestion, a lot of the things that you're asking
are covered in much more extent and accuracy in the chapter 13.5 of the
Stroustrup.

Regards,

Zeppe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top