constexpr literal initialization with a constexpr

会有一股神秘感。 提交于 2021-02-10 06:15:17

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37767483/constexpr-literal-initialization-with-a-constexpr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!