Template function overloading with identical signatures, why does this work?

泪湿孤枕 提交于 2019-12-03 11:37:32

The first function is considered to be more specialized than the first.

The function

int foo(typename T::type)

could match

template <typename S,typename T> int foo(S s)

by using T::type as the value for parameter S, but

int foo(S s)

will not match

template <typename S,typename T> int foo(typename T::type)

because T cannot be deduced.

The logic is layed out in the C++03 standard in section 14.5.5.2, and in the C++11 standard in section 14.5.6.2.

Here is the idea: To see if one function is more specialized than another, you invent values for each template parameter for the first function, and then see if the second function could match the resulting signature. You also invent values for the template parameters of the second function, and see if the first function will match the resulting signature. If the second function can match the first one, then the second function can't be more specialized than the first one. If, in addition to that, the first function can't match the second, then the first must be more specialized than the second. That is the case you have.

Here's an even further simplification of the phenomenon:

#include <stdio.h>

template<typename T>
void foo(int arg) {
    printf("a\n");
}

template<typename T>
void foo(T arg) {
    printf("b\n");
}

int main(int argc, char* argv[]) {
    foo<int>(3);   // prints "a"
    foo(3);        // prints "b"

    return 0;
}

Template parameters can either be passed explictly through angled brackets or they can be resolved through deduction. If a parameter isn't specified explicitly, it must be deducible using the function's arguments.

So, in the case of foo(3), template 'a' won't work, because the parameter T isn't explicitly specified and can't be deduced. In the case of foo<int>(3), both templates could work. In fact, if you comment out template 'a', a call to foo<int>(3) will print "b". So the question is, why is template 'a' prefered? The key here is "partial ordering":

http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fpartial_ordering_funct_templ.htm

I see now that someone else has already answered (I'm bad at answering questions quickly), so I'm going to just wrap this up now and say that template 'a' is more specialized like Vaughn said.

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