简体   繁体   中英

Is a templated and a nontemplated version of the same function considered an overload?

A very formal question: is this considered an overload? Is removing the template fundamentally different than only overloading on arguments?

template<class T> void myFunction(const T& t) {}
void myFunction(const double& t) {}

Then the follow up question, is it better to follow this approach or to use template specialization, instead of the overload?

template<> void myFunction(const double& t) {}

First of all, according to the standard (start of §13): “When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded.[...]Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.” So clearly, your two declarations are overloads.

If you call myFunction( 3.14159 ) , then the template will be instantiated with the same signature as the non-template, and both will be exact matches. In this case (§13.3.1):

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...] — F1 is a non-template function and F2 is a function template specialization, [...]

The standard has specified your exact case.

With regards to the alternative of specializing the function: specializations may be overloads according to the definition above, but they do not participate in overload resolution. Specializations work differently: overload resolution first occurs without them; then, if overload resolution has chosen the template, and there is a specialization for the instantiation type(s), the specialization is used, rather than the generic instantiation of the template. Generally speaking, the results are the same, although http://www.gotw.ca/publications/mill17.htm points out one exotic (and badly written?) case where they aren't. Still, to me at least, it seems more natural to provide the overloaded function, rather than the template specialization. Most of the time, anyway. (There is one real exception: it's sometimes useful to not provide a generic implementation, but only specializations. In my experience, this situation usually occurs with traits classes, but it can occur for an individual function as well. In such cases, of course, you do specialize the template; you cannot use it otherwise.)

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