简体   繁体   中英

Why is this not a partial specialization of a function template?

Let's consider the following code:

template<typename T>
void func(T);
template<typename T>
void func(T*); // an overload

I know that the second declaration is an overload, not the partial specialization:

template<typename T>
void func<T*>(T*); // not allowed by C++ standard

But I wonder how is it different from a partial specialization? It give us the same functionality as the partial specialization would give, doesn't it?

But I wonder how is it different from a partial specialization?

It's different in that it's not a specialization. A template specialization is an alternate implementation of a primary template, used when certain template arguments are provided. When you apply a set of arguments to a template name in code, that causes the compiler to invoke template instantiation machinery. Part of that is to check for explicit specializations of the primary template and use them if they match those arguments.

With a function overload, that doesn't happen. Overload resolution machinery is used instead.

Different means to accomplish the same ends.

If you're wanting the details, a function is more than a name; it is a name and its signature. So a function with the same name but a different signature is a different function. Thus, that line doesn't declare a specialization of the same template function; it declares a new primary template.

It give us the same functionality as the partial specialization would give, doesn't it?

There are probably cases where partial specialization could do something more conveniently than overloading, but those are probably based on SFINAE or other meta-programming tricks. Yes, partial specialization could do most of what overloading does.

But you still need overloading rules, regardless of whether function partial specialization exists or not. You need those rules for non-template cases and cases where you can overload a template function with non-template versions. Or that have more arguments or fewer than the primary template. You need to be able to have some constructors which are templates and some which are not.

So there are going to be rules about how overloading works with template functions no matter what.

So the better way to say what you're saying is that function overloading largely makes function partial specialization superfluous (which is probably why it doesn't exist). Or even better, class template partial specialization is a way to give class templates something similar to the overloading features of functions.

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