When overloading a method, I believe the compiler will choose the simpler match when multiple matches are available.
Consider this code:
#include <iostream>
#include <string>
struct A {
static void foo(const char *str) {
std::cout << "1: " << str << std::endl;
}
template<int N> static void foo(const char (&str)[N]) {
std::cout << "2: " << str << std::endl;
}
};
int main()
{
A::foo("hello");
}
The output is 1: hello
. Yet, if I comment out the static void foo(const char *str)
method, it compiles fine and outputs 2: hello
.
How can I have both methods on a class such that arrays with known size will call the template method, and pointer types call the non-template method?
I tried the following:
struct A {
template<class _Ty = char>
static void foo(const _Ty *str) {
std::cout << "1: " << str << std::endl;
}
template<int N> static void foo(const char (&str)[N]) {
std::cout << "2: " << str << std::endl;
}
};
But g++ gives me the following error:
In function 'int main()':
17:17: error: call of overloaded 'foo(const char [6])' is ambiguous
17:17: note: candidates are:
6:15: note: static void A::foo(const _Ty*) [with _Ty = char]
10:32: note: static void A::foo(const char (&)[N]) [with int N = 6]
_Ty
, that's reserved to the implementation. Second,const T * const & str
. – Bowsprit_Ty
in your code by nothing. This is why you should not use these names. And this is why the standard uses it. – Castro