注意:这不是关于使用字符串来选择 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/