dimanche 24 septembre 2017

ambiguous call of overloaded template with parameter (const T&, const T&) or (const char (&)[N], const char (&)[M])

For the following code:

#include <iostream>
using std::cout; using std::endl;

template <typename T>
int compare(const T&, const T&) {
    cout << __PRETTY_FUNCTION__ << endl;
    return 0;
}
template <size_t N, size_t M>
int compare(const char (&)[N], const char (&)[M]) {
    cout << __PRETTY_FUNCTION__ << endl;
    return 0;
}

int main(int argc, char *argv[]) {
    compare("hi", "is");
}

When I compiles the code with g++ -std=c++1y, it complains:

error: call of overloaded ‘compare(const char [3], const char [3])’ is ambiguous
     compare("hi", "is");

According to the rules of template overloading, viable functions are:

compare(const T&, const T&) with T = char [3]
compare(const char (&)[N], const char (&)[M]) with N = 3ul, M = 3ul

They both provide an equally good (i.e., exact) match to the call. So I should check which one is more specialized.

But according to my limited knowledge, const T& is more general than const char (&)[N]. So I think that compare(const char (&)[N], const char (&)[M]) is more specialized. But why is this call ambiguous?

Aucun commentaire:

Enregistrer un commentaire