重载 std::字符串运算符+ 用于打印枚举名称

Overload std::string operator+ for printing enum name

本文关键字:打印 枚举 用于 std 字符串 运算符 重载      更新时间:2023-10-16

我有一个枚举

enum ft_dev_type
{
SPI_I2C,
GPIO
};

我希望能够构造这样的字符串

std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C"

为此,我正在尝试重载 + 运算符

std::string operator+(const ft_dev_type type) const
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
}

但我得到

向字符串添加"ft_dev_type"不会追加到字符串。

如何正确重载 + 运算符?

[编辑] 下面是类


class driver_FT4222
{
public:
driver_FT4222() {}
enum ft_dev_type
{
SPI_I2C,
GPIO
};
std::string operator+(const ft_dev_type type) const //this line is probably wrong
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
}
void doSomething()
{
...
std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C"
std::cout <<s;
...
}
}

看来你想要免费功能:

std::string operator+(const char* s, const ft_dev_type type)
{
switch (type)
{
case SPI_I2C: return s + std::string("SPI_I2C");
case GPIO: return s + std::string("GPIO");
}
throw std::runtime_error("Invalid enum value");
}

(std::string类似

...但更好的IMO有一个to_string

std::string to_string(const ft_dev_type type)
{
switch (type)
{
case SPI_I2C: return std::string("SPI_I2C");
case GPIO: return std::string("GPIO");
}
throw std::runtime_error("Invalid enum value");
}

要有

std::string s = "enum =" + to_string(SPI_I2C);