重载 std::字符串运算符+ 用于打印枚举名称
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"不会追加到字符串。
如何正确重载 + 运算符?
[编辑] 下面是类
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);
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 打印没有铸件的枚举可以在C++中吗?
- 重载 std::字符串运算符+ 用于打印枚举名称
- 将 Qt 属性枚举值打印为键字符串
- 打印枚举文本而不是值C++
- 是否有任何操纵器将枚举值打印为字符串?
- 如何在C 中相互依存的枚举中打印值的名称
- 枚举类的GoogleTest测试错误打印
- 运算符<< 是模棱两可的打印枚举值,基础类型为 short
- 打印出枚举标志中的选定项目
- 打印枚举值
- 模板化用于打印枚举的流操作符
- 在使用特定枚举标识符时打印出静态"deprecate"警告消息并附上建议的更正?
- 如何在c++中从枚举类中打印出字符串
- 枚举类型打印出相应的 int