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

时间:2020-06-12 16:22:56

标签: c++

我有一个枚举

    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”不会追加到字符串中。

如何正确重载+运算符?

[edit]下面是课程


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;
        ...
    }
}

1 个答案:

答案 0 :(得分:5)

似乎您想要免费功能:

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);
相关问题