Explicit Feature Template Specification - Why?

I continue to read and research, various posts, C ++ books, articles, and so far no one has explained the rational design to me. That doesn't make sense, and it really bothers me. The whole point of the template is to parameterize types for functions (or classes, but I'm talking specifically about the function template, not the class). Why use a funny template syntax without a 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 understanding, and I understand that specializing function templates is not so useful in practice, but I still want to understand why it was ever invented. The one who invented this should have had a reason that seemed convincing enough at the time.

Thanks.

+6
source share
1 answer

Great question! Function template specialization is a small niche and is usually not worth it. You may be a little confused for a reason.

You ask, "what's the fun syntax of a template without a type parameter?" Much! Specialized templates are very important and useful, and the good old swap example is a classic reason to consider it. The template embodies the idea of ​​a general algorithm that works with any type, but often, if you know a little about the type you can add to a much better algorithm without calling code that requires you to know that something else is happening under the hood. Only the compiler knows, and it pulls the best implementation for real types at the moment when the algorithm is created with specific types, so your fast swap happens without a sorting algorithm that requires special cases. Specialization is a key part of creating universal programming useful in the real world (or we will have to use universal versions to get the required performance).

The specialization of the function template, although a bit niche, is for more obscure reasons. Think you read the Herb Sutter Summary ? So, if you do not want to be caught, it is recommended that you avoid specialized function templates. ( std::swap is an example of at least something that you need to specialize and not overload if you want to be ultra-compliant with the standard. We do this extensively in our code base here, and it works well in practice, although overloading, probably will work well enough.)

So, please specialize in everything that you like. Having specialized class templates that are far from ridiculous is often vital, but specializing function templates is not so useful.

+1
source

All Articles