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

强颜欢笑 提交于 2019-12-10 20:58:33

问题


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) {}

回答1:


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.)



来源:https://stackoverflow.com/questions/28168290/is-a-templated-and-a-nontemplated-version-of-the-same-function-considered-an-ove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!