c++ - 使用 std::string 在 switch-case block 中返回字符串常量

标签 c++ c++14

注意:这不是关于使用字符串来选择 switch-case block 中的执行路径。

C++ 中的一个常见模式是使用 switch-case block 将整数常量转换为字符串。这看起来像:

char const * to_string(codes code)
{
    switch (code)
    {
        case codes::foo: return "foo";
        case codes::bar: return "bar";
    }
}

但是,我们是在C++中,所以使用std::string更合适:

std::string to_string(codes code)
{
    switch (code)
    {
        case codes::foo: return "foo";
        case codes::bar: return "bar";
    }
}

然而,这会复制字符串文字。也许更好的方法是:

std::string const & to_string(codes code)
{
    switch (code)
    {
        case codes::foo: { static std::string str = "foo"; return str; }
        case codes::bar: { static std::string str = "bar"; return str; }
    }
}

但这有点丑陋,涉及更多样板。

对于使用 C++14 的这个问题,什么被认为是最干净、最有效的解决方案?

最佳答案

This however copies the string literal.

是也不是。它确实会复制字符串文字,但不一定会分配内存。检查您的实现 SSO 限制。


你可以使用std::string_view:

constexpr std::string_view to_string(codes code) {
    switch (code) {
        case codes::foo: return "foo";
        case codes::bar: return "bar";
    }
}

您可以找到许多向后移植的版本,例如 this one

但是,有时 char const* 是正确的抽象。例如,如果您将该字符串转发到需要以空字符结尾的字符串的 API,您最好返回一个 c 风格的字符串。

关于c++ - 使用 std::string 在 switch-case block 中返回字符串常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54518190/

相关文章:

c++ - 可以从进程核心访问释放的内存段吗?

c++ - 是否有一种 STL 方法可以对指针 vector 进行深度复制?

c++ - 使用元编程展开嵌套循环

c++ - 每种类型的编译时 typeid

c++ - 标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动 func?

c++ - 来自 boost::operators 的意外行为

c++ - 在 boost python 中公开 C++ 接口(interface)

c++ - 我想发送固定数量的字节来表示可以解析为整数值的数值

c++ - 获取 vector 的总和

c++ - 属性存在通用检查