【问题标题】:C++: concatenate an enum to a std::stringC++:将枚举连接到 std::string
【发布时间】: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++


【解决方案1】:

您传递给运算符的是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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2015-09-21
    相关资源
    最近更新 更多