Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferring method with size template over method with pointer type

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]
like image 285
GaspardP Avatar asked Nov 24 '16 03:11

GaspardP


1 Answers

As suggested by T.C., 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 did not have to template the pointer method since it opens the door to misuses with unexpected types, but I can live with this solution.

like image 143
GaspardP Avatar answered Nov 15 '22 06:11

GaspardP