When overloading a method, I believe that the compiler will choose a simpler match if multiple matches are available.
Consider this code:
#include <iostream>
Output 1: hello
. However, if I comment on the static void foo(const char *str)
method, it compiles fine and outputs 2: hello
.
How can I use both methods in a class so that arrays with a known size invoke a template method and pointer types invoke a method without templates?
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]
source share