C++:将枚举连接到 std::string

C++: concatenate an enum to a std::string

本文关键字:std string 枚举 C++ 连接      更新时间:2023-10-16

所以我试图将枚举连接到一个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;