AlexTheo
AlexTheo

Reputation: 4164

constexpr literal initialization with a constexpr

simple example here:

 static constexpr const char literal1[] = "abcde"; 
 static constexpr const char literal2[] = literal1;

compilation error. How to make it work and why it doesn't?

Upvotes: 2

Views: 1480

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69854

update:

In response to comment, here's a revised verson.

The class immutable::string models a constexpr string-like object which tracks the original string literal. It's very similar to c++17's string_view except that the template constructor avoids the need for a call to strlen at any time.

#include <cstdint>
#include <array>
#include <utility>
#include <iostream>

namespace immutable {

    struct string
    {
        template<std::size_t N>
        constexpr string(const char (&s)[N])
        : _data(s)
        , _size(N-1)
        {}

        constexpr const char* data() const { return _data; }
        constexpr std::size_t size() const { return _size; }

        const char* const _data;
        const std::size_t _size;
    };
    std::ostream& operator<<(std::ostream& os, string s)
    {
        return os.write(s.data(), s.size());
    }
}


static constexpr auto literal1 = immutable::string("abcde");
static constexpr auto literal2 = literal1;

int main()
{
    std::cout << literal1 << std::endl;
    std::cout << literal2 << std::endl;
}

Upvotes: 4

Related Questions