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

Posted by user1843978 on Stack Overflow See other posts from Stack Overflow or by user1843978
Published on 2012-12-20T04:40:37Z Indexed on 2012/12/20 5:03 UTC
Read the original article Hit count: 114

Filed under:
|
|

Minimal program:

#include <stdio.h>

#include <type_traits>

template<typename S, typename T>
int foo(typename T::type s) {
    return 1;
}

template<typename S, typename T>
int foo(S s) {
    return 2;
}

int main(int argc, char* argv[]) {
    int x = 3;
    printf("%d\n", foo<int, std::enable_if<true, int>>(x));

    return 0;
}

output:

    1 

Why doesn't this give a compile error? When the template code is generated, wouldn't the functions int foo(typename T::type search) and int foo(S& search) have the same signature?

If you change the template function signatures a little bit, it still works (as I would expect given the example above):

template<typename S, typename T>
void foo(typename T::type s) {
    printf("a\n");
}

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

Yet this doesn't and yet the only difference is that one has an int signature and the other is defined by the first template parameter.

template<typename T>
void foo(typename T::type s) {
    printf("a\n");
}

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

I'm using code similar to this for a project I'm working on and I'm afraid that there's a subtly to the language that I'm not understanding that will cause some undefined behavior in certain cases. I should also mention that it does compile on both Clang and in VS11 so I don't think it's just a compiler bug.

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates