Preference method with size pattern by method with pointer type

When overloading a method, I believe that the compiler will choose a simpler match if 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"); } 

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] 
+6
source share
1 answer

As suggested by TC, this works:

 struct A { template<class T, typename = typename std::enable_if<std::is_same<T, char>::value>::type> static void foo(const T * const & 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("hello1"); const char *c = "hello2"; A::foo(c); char *c2 = new char[7]; ::strcpy(c2, "hello3"); A::foo(c2); // does not compile // int *c3; // A::foo(c3); } 

Outputs:

 2: hello1 1: hello2 1: hello3 

I wish I had to create a pointer method template, as it opens the door to abuses with unexpected types, but I can live with this solution.

+1
source

Source: https://habr.com/ru/post/1012610/


All Articles