Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous error with char* and char[N]

Tags:

c++

templates

Can someone help me to understand is this correct behavior or not.

Consider this example:

#include <iostream>
using namespace std;

template <typename T>
struct test {
};

template <typename T>
bool operator==(const test<T>& obj, const T* arr) {
    return true;
}

template <typename T, size_t TN>
bool operator==(const test<T>& obj, const T (&arr)[TN]) {
    return false;
}

int main() {
    cout << ( test<char>() == "string" ) <<endl;
    return 0;
}

With gcc 4.7.3 it compiles just fine and outputs '0' as expected.

But with Visual Studio compiler it reports an ambiguous error (C2593).

Who is right in this situation and what does standard say about it?

Thank you.

like image 361
Tony Avatar asked Dec 23 '13 16:12

Tony


2 Answers

Using fairly recent versions (i.e., recent heads of the development branches) of gcc and clang also show an ambiguity. I would have thought that the overload taking an array is better but it seem the code is ambiguous. I haven't tracked down the relevant clauses in the standard, yet, however.

like image 54
Dietmar Kühl Avatar answered Nov 07 '22 04:11

Dietmar Kühl


As I understand simple overloading would not work in new versions of gcc and already doesn't work in VC10.

So, if someone wonders how to fix this issue here is a solution:

template <typename T>
struct test {
};

template <typename T>
struct parse {
};

template <typename T>
struct parse<T*> {
    static bool run() {
        return true;
    }
};

template <typename T, size_t TN>
struct parse<T[TN]> {
    static bool run() {
        return false;
    }
};

template <typename T, typename T2> 
bool operator==(const test<T>& obj, const T2& obj2) {
    return parse<T2>::run();
}

int main() {
    cout << ( test<char>() == "string" ) <<endl;
    cout << ( test<char>() == (char*)"string" ) <<endl;
    return 0;
}

Compiled it with VC10, gcc-4.6.3 and gcc-4.8.1. Seems to be working correctly.

like image 1
Tony Avatar answered Nov 07 '22 04:11

Tony