Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 string literal template argument working example

Could someone post a minimal reproducible example of C++20's feature string template as template argument?

this one from ModernCpp does not compile:

template<std::basic_fixed_string T>
class Foo {
    static constexpr char const* Name = T;
public:
    void hello() const;
};

int main() {
    Foo<"Hello!"> foo;
    foo.hello();
}

I've managed to write a working solution based on this Reddit post:

#include <iostream>

template<unsigned N>
struct FixedString 
{
    char buf[N + 1]{};
    constexpr FixedString(char const* s) 
    {
        for (unsigned i = 0; i != N; ++i) buf[i] = s[i];
    }
    constexpr operator char const*() const { return buf; }

    // not mandatory anymore
    auto operator<=>(const FixedString&) const = default;
};
template<unsigned N> FixedString(char const (&)[N]) -> FixedString<N - 1>;

template<FixedString Name>
class Foo 
{
public:
    auto hello() const { return Name; }
};

int main() 
{
    Foo<"Hello!"> foo;
    std::cout << foo.hello() << std::endl;
}

Live Demo

but does provide a custom implementation for a fixed string. So what should be the state-of-the-art implementation by now?

like image 853
Moia Avatar asked Jun 08 '20 15:06

Moia


1 Answers

P0259 fixed_string has been retired on the basis that most of its use cases are better achieved via P0784 More constexpr containers (aka constexpr destructors and transient allocation) - i.e. being able to use std::string itself within constexpr context.

Of course, even if you can use std::string in constexpr, that doesn't make it usable as an NTTP, but it doesn't look like we're going to get a structural string class into the Standard any time soon. I would recommend using your own structural string class for now, being ready to alias it to an appropriate third-party class should one emerge in a popular library, or to a standard one if and when that happens.

like image 165
ecatmur Avatar answered Nov 02 '22 06:11

ecatmur