char*和char[N]出现不明确的错误
Ambiguous error with char* and char[N]
有人能帮我理解这种行为是否正确吗。
考虑这个例子:
#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编译。似乎工作正常。
相关文章:
- Visual C++(VS2017)中用户定义的转换不明确
- 重载类方法的不明确调用
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 为函数定义符号不明确的指针参数
- 父类的私有函数会导致对具有相同名称和相似参数的子类中的公共函数的不明确调用
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 对重载函数find_first_not_of的不明确调用
- 不明确的成员模板查找
- gcc出现不明确的模板实例化错误
- 调用'Node'构造函数是不明确的
- 如何解决不明确的运算符过载问题?
- 重载运算符'<<'的使用不明确(操作数类型'ostream'(也称为"basic_ostream<char>")和"Person")
- 重载的 'func(char*&)' 的调用是不明确的
- 重载运算符'>>'的使用不明确(操作数类型'istream'(又名"basic_istream<char>")和"MyIncreEx")
- 对重载'swap(char&, char&)'的调用不明确
- C++ 编译错误:重载的"<function_name>(char*&)"调用不明确
- char*和char[N]出现不明确的错误
- 2013和GCC之间的全局函数和不明确的参数NULL与char*
- 错误:Map<int 中运算符 = 的重载不明确,std::basic_string >::<char>Elem::t3 = 0