C++:将枚举连接到 std::string
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:运算符+(常量字符*,长整型)在文件中包含的文件中.cpp:4:0: file.h:18:20: 注意:候选 2
: std::string operator+(std::string, DATATYPE) inline std::string operator+(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
编译,你会得到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;
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL