【发布时间】:2015-03-02 20:53:52
【问题描述】:
所以我试图将枚举连接到 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 = "illegal type for operation" + dt1; absyn.cpp:642:55: 注意: 候选 1: operator+(const char*, long int) 在 file.cpp:4:0 包含的文件中:file.h:18:20:注意:候选 2:std::string operator+(std::string, DATATYPE) inline std::string operator+(std::string str , const DATATYPE dt){
这个警告到底是什么意思,如何解决?
【问题讨论】:
-
DATATYPE是int类型,这意味着编译器无法区分,应该调用什么。您可以尝试使用 C++11 中的枚举类。
-
没有收到任何错误ideone.com/Xsggwz
-
我建议不要使用地图,而是使用一些静态辅助结构来配合您的枚举和
to_string函数,如此处所述 stackoverflow.com/questions/9150538/…
标签: c++