简体   繁体   中英

Explicit function template specialization - Why?

I keep reading and researching, different posts, c++ books, articles and so far nobody has explained the rational for this construct to me. It makes no sense and its really bugging me. The whole point of a template is to parameterize types to functions (or classes, but i'm talking specifically function template, not class). Why use funny template syntax without the type parameter???

//this seems ridiculous. why would anybody ever use this?
template<> void Swap(int & a , int & b){}
//I would always use this if I needed to take care of a special case, no?
void Swap(int & a , int & b){}

What am I missing? I would really appreciate some insight, and I do understand that function template specialization is not all that useful in practice anyway, but i still want to understand why it was ever invented in the first place. Whoever came up with it must have had a reason which seemed compelling enough at the time.

Thanks.

Great question! Function template specialisation is a bit niche and not generally worth it. You might be a bit confused as to the reason though.

You ask "what's the funny template syntax without a type parameter?" Plenty of use! Specialising templates is very important and useful, and the good old swap example is a classic reason to consider it. A template embodies the idea of a generic algorithm that works with any type, but often if you know a bit about the type you can drop in a much better algorithm, without calling code needing to know that anything different is happening under the hood. Only the compiler knows and it pulls in the best implementation for the real types at the point where the algorithm is instantiated with specific types, so your fast swap happens without the sorting algorithm needing special cases. Specialisation is a key part of making generic programming useful in the real world (or we'd have to use un-generic versions to get the performance we need).

Function template specialisation though is a bit niche, for more obscure reasons. I guess you've read Herb Sutter's summary ? So, if you don't want to be caught out, it's a good idea to avoid specialising function templates. ( std::swap is an example though of something you have to specialise rather than overload if you want to be ultra-conformant to the standard. We do this widely in our codebase here and it works well in practice, though overloading would probably work well enough too.)

So, please, specialise away all you like. Having class template specialisations, far from being "ridiculous" is often vital, but function template specialisation isn't as useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM