Template instantiation error

c++, templates

Solution

As stated in Greg's answer and comments, the two different array types (since that's what string literals are) is the problem. You may want to leave the function as-is for generic types, but overload it for character pointers and arrays, this is mostly useful when you want to treat them slightly differently.

void compare(char const* a, char const* b) {
    // do something, possibly use strlen()
}

template<int N1, int N2>
void compare(char const (&a)[N1], char const (&b)[N2]) {
    // ...
}

If you want to specify that compare should take character pointers explicitly, then the arrays will automatically convert:

compare<char const*>("aa", "bbbb");

On the other hand, maybe compare could be written to work with two different types? This can be useful for other types as well, e.g. maybe it calls `f(a)` if `a.size() < b.size()`, and `f(b)` otherwise (with `f` overloaded). (T1 and T2 are allowed to be the same type below, and this would replace your function instead of overloading it as the above two.)

template<typename T1, typename T2>
void compare(T1 const& a, T2 const& b) {
    // ...
}

Problem

I have template function "compare" defined as below. ``` #include<iostream> using namespace std; template<typename T> void compare(const T&a, const T& b) { cout<<"Inside compare"<<endl; } main() { compare("aa","bb"); compare("aa","bbbb"); } ``` When i instantiate compare with string literals of same length, the compiler doesnot complain. When i do it with literals of different length,it says "error: no matching function for call to compare(const char[3],const char[5])" I am confused as compare function should be instantiated with character pointer rather than character array. Should not string literals always decay to pointer?

Original source