头文件中的字符串视图文字

lee*_*ker 2 c++ string-literals string-view c++17

我有一个有一堆常量字符串的类,形式如下:

using namespace std::string_view_literals;
class T {
  static const constexpr std::string_view something1 = "Alice"sv;
  static const constexpr std::string_view something2 = "Bob"sv;
  static const constexpr std::string_view something3 = "Charlie"sv;

  ...
};
Run Code Online (Sandbox Code Playgroud)

我目前usingstring_view_literals命名空间,但这不是头文件中的好习惯,并生成警告:

Using namespace directive in global context in header [-Wheader-hygiene] (铛)

literal operator suffixes not preceded by '_' are reserved for future standardization [-Wliteral-suffix] (gcc7)

我想看看其他选择.

  1. 忽略警告
  2. 直接导入我正在使用的一个文字,而不是整个命名空间

    using std::string_view_literals::operator""sv

  3. 由于这是一个constexpr常量,也许我应该直接调用构造函数,因为它知道它没有运行时内存或CPU开销:

    static const constexpr something1 = std::string_view("Alice");

  4. 别的什么?

Bar*_*rry 5

这很短,不会污染任何东西:

class T {
    using sv = std::string_view;
    static constexpr auto something1 = sv("Alice");
    static constexpr auto something2 = sv("Bob");
    static constexpr auto something3 = sv("Charlie");
};
Run Code Online (Sandbox Code Playgroud)

如果你真的想要使用文字,你可以将你的类包装在另一个不想要命名的类中namespace,然后将它带回到外部命名空间:

namespace _private {
    using namespace std::string_view_literals;

    class T {
        static constexpr auto something1 = "Alice"sv;
        static constexpr auto something2 = "Bob"sv;
        static constexpr auto something3 = "Charlie"sv;
    };
}

using _private::T;
Run Code Online (Sandbox Code Playgroud)

请注意,写入static constexpr const是多余的.constexpr变量是隐含的const.

  • 第一个强加的解决方案是错误的。`sv("Alice")` 仍然有效地调用“const char*”构造函数,强制对参数进行 strlen 调用 --> 破坏了文字的目的。`std::string_view("alice\0foo").length(); //--> 5` `"alice\0foo"sv.length (); // --> 9` (3认同)