Template overload question

So I have this template function which takes two parameters. The parameters can have two different types, but I want the function to behave differently if both types are the same.

SO:

1
2
3
4
5
6
7
8
9
10
11
template <typename T,typename U>
void func(T t,U u)
{
  // func "A"
}

template <typename T>
void func(T t,T u)
{
  // func "B"
}


It makes sense to me that the compiler would prefer to use B whenever possible, and will use A only if the types are different (which means B can't be used).

But is this the case? Is it reliable?

Thanks!
Last edited on
did u already try it out?... what are your results?...


in my opinion this would make sence especially in terms of compiling performance... but im not someone to rely on when concering performance, sorry^...
Last edited on
The compiler behaves straightforwardly: if two parameters are different it calls func"A", and func"B" is called otherwise. Is there another option?

If you you are interested, this is true for MSVC and gcc.
To be standard conform, the compiler must prefer B to A if both template arguments are of equal type.

B is "more specialized" than A, because you can instantiate A with deduced parameters from B (A::func<T,T> is valid), but not vice versa (B::func<T,U> is not valid - T and U are unique types in the test). Compiler have to choose the "most specialized" function.

So go ahead. It's reliable. ;)

Ciao, Imi.
Rock on.

Thanks everyone =)
Topic archived. No new replies allowed.