Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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">;
}

>Solution :

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>;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading