注意:这不是使用字符串来选择switch-case块中的执行路径.
C++中的一个常见模式是使用switch-case块将整数常量转换为字符串.这看起来像:
char const * to_string(codes code)
{
switch (code)
{
case codes::foo: return "foo";
case codes::bar: return "bar";
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我们使用的是C++,因此使用std :: string更合适:
std::string to_string(codes code)
{
switch (code)
{
case codes::foo: return "foo";
case codes::bar: return "bar";
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这会复制字符串文字.也许更好的方法是:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
但这有点难看,涉及更多的样板.
什么被认为是使用C++ 14解决这个问题最干净,最有效的解决方案?
然而,这会复制字符串文字.
是的,不是.它确实会复制字符串文字,但不一定要分配内存.检查您的实施SSO限制.
你可以使用std::string_view:
constexpr std::string_view to_string(codes code) {
switch (code) {
case codes::foo: return "foo";
case codes::bar: return "bar";
}
}
Run Code Online (Sandbox Code Playgroud)
你可以找到许多回迁版本像这样一个
但是,有时候a char const*是正确的抽象.例如,如果您要将该字符串转发到需要空终止字符串的API中,那么最好将其返回到ac样式字符串.
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |