char*和char[N]出现不明确的错误

Ambiguous error with char* and char[N]

本文关键字:char 不明确 错误      更新时间:2023-10-16

有人能帮我理解这种行为是否正确吗。

考虑这个例子:

#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;
}

使用gcc 4.7.3,它编译得很好,并按预期输出"0"。

但使用Visual Studio编译器,它会报告一个ambiguous error (C2593)

在这种情况下谁是对的,standard对此有何看法?

谢谢。

使用gcc和clang的最新版本(即开发分支的最新负责人)也会显示出歧义。我本以为重载一个数组会更好,但代码似乎不明确。然而,我还没有找到标准中的相关条款。

据我所知,简单的重载在新版本的gcc中不起作用,而且在VC10中已经不起作用了。

因此,如果有人想知道如何解决这个问题,这里有一个解决方案:

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;
}

用VC10、gcc-4.6.3和gcc-4.8.1编译。似乎工作正常。