[英]Overload std::string operator+ for printing enum name
我有一个枚举
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' 添加到字符串不会 append 到字符串。
如何正确重载 + 运算符?
[编辑] 下面是 class
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;
...
}
}
看来您想要免费的 function:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.