简体   繁体   中英

C++ Constexpr Template Structs with String Literals

Currently using C++20, GCC 11.1.0.

I'm trying to create types in a namespace with a unique value and name . I came up with this structure specifically to be able to access the variables with the scope resolution operator like so: foo::bar::name . However, I have no idea how to initialize the name variable. I tried adding a second non-type parameter const char* barName , but it wouldn't let me use string literals as template arguments.

Code:

namespace foo
{
    template<uint32_t id>
    struct bar
    {
        static constexpr uint32_t value {id};
        static constexpr std::string_view name {};
    };

    using a = bar<0>;
    using b = bar<1>;
}

Error Code:

namespace foo
{
    template<uint32_t id, const char* barName>
    struct bar
    {
        static constexpr uint32_t value {id};
        static constexpr std::string_view name {barName};
    };

    using a = bar<0, "a">;
    using b = bar<1, "b">;
}

Since we can't pass string literals as template arguments, we have to use some other way. In particular, we can have a static const char array variable as shown below:

static constexpr char ch1[] = "somestrnig";
static constexpr char ch2[] = "anotherstring";
namespace foo
{   //--------------------vvvvvvvvvvvvvvvv--->added this 2nd template parameter
    template<uint32_t id, const char* ptr>
    struct bar
    {
        static constexpr uint32_t value {id};
        //--------------------------------------vvvv-->added this
        static constexpr std::string_view name {ptr};
    };
    //---------------vvv----->added this
    using a = bar<0, ch1>;
    using b = bar<1, ch2>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM