Class containing Constants of std::string

前端 未结 2 1289
一生所求
一生所求 2021-01-26 04:14

So I\'m currently working on a school-project with C++, which I\'m not really familiar with. I would like to create a class, containing all my constants (string,int,double,own c

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 04:38

    In C++17, the recommended way of defining string constants if by using an inline constexpr std::string_view. Example:

    namespace reference
    {
        inline constexpr std::string_view deepSeaPath{R"(something)"};
        // ...
    }
    

    This is great because:

    • std::string_view is a lightweight non-owning wrapper that can efficiently refer to string literals without any additional costs.

    • std::string_view seamlessly interoperates with std::string.

    • Defining the variables as inline prevents ODR issues.

    • Defining the variables as constexpr makes it clear to both the compiler and other developers that these are constants known at compile-time.


    If you do not have the luxury of using C++17, here's a C++11 solution: define your constants as constexpr const char* in a namespace:

    namespace reference
    {
        constexpr const char* deepSeaPath{R"(something)"};
        // ...
    }
    

提交回复
热议问题