2

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?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
AlexTheo
  • 4,004
  • 1
  • 21
  • 35
  • Arrays cannot be initialized from other arrays. (String literals are an exception.) – Kerrek SB Jun 11 '16 at 19:02
  • 1
    [This](http://melpon.org/wandbox/permlink/gM5T1bdeqCNItFdI) is the best I can think of. – Kerrek SB Jun 11 '16 at 19:05
  • You could also use the `str_const` template from Scott Schurr's Boost Con slides, I think. http://stackoverflow.com/questions/27291903/passing-constexpr-objects-around – Chris Beck Jun 11 '16 at 19:30

1 Answers1

4

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;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142