[英]C++: concatenate an enum to a std::string
所以我试图将枚举连接到std :: string。 为此,我编写了以下代码。
typedef enum { NODATATYPE = -1,
DATATYPEINT,
DATATYPEVARCHAR
} DATATYPE;
inline std::string operator+(std::string str, const DATATYPE dt){
static std::map<DATATYPE, std::string> map;
if (map.size() == 0){
#define INSERT_ELEMENT(e) map[e] = #e
INSERT_ELEMENT(NODATATYPE);
INSERT_ELEMENT(DATATYPEINT);
INSERT_ELEMENT(DATATYPEVARCHAR);
#undef INSERT_ELEMENT
}
return str + map[dt];
}
和
DATATYPE dt1 = DATATYPEINT;
std::string msg = "illegal type for operation" + dt1;
我在编译此代码时收到以下警告。
警告:ISO C ++表示这些含义不明确,即使第一个的最差转换比第二个的最差转换更好:std :: string msg =“操作的非法类型” + dt1; absyn.cpp:642:55:注意:候选1:运算符+(const char *,long int)在file.cpp:4:0:file.h:18:20包含的文件中:注意:候选2:std ::字符串运算符+(std :: string,DATATYPE)内联std :: string运算符+(std :: string str,const DATATYPE dt){
此警告究竟是什么意思,以及如何解决?
您传递给运算符的是const char*
(表示字符串文字)和DATATYPE
。 由于没有重载operator+(const char*, DATATYPE)
,编译器会在可以隐式转换参数的位置寻找重载。 候选人在警告中:
operator+(const char*, long int)
operator+(std::string, DATATYPE)
第一个参数可以从const char*
转换为std::string
,第二个参数可以从DATATYPE
转换为long int
。 因此,第一个重载在第一个参数的基础上“获胜”了过载解决方案,第二个重载在第二个参数的基础上“获胜”了。 由于在这两个参数的基础上都没有过载“赢得”解决方案,因此它们是模棱两可的。
编译器警告您,因为它怀疑它选择的重载可能不同于您要调用的重载。 如果在gcc上使用-pedantic
进行编译, -pedantic
error: ambiguous overload for
...而不只是警告。
解决方案是通过传递完全匹配的类型的参数来消除呼叫的歧义。 一种简单的方法是:
std::string msg = std::string("illegal type for operation") + dt1;
或在C ++ 14中更好
std::string msg = "illegal type for operation"s + dt1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.