constexpr length of a string from template parameter

孤者浪人 提交于 2019-12-06 16:48:53
Jarod42

To concatenate string at compile time,
with gnu extension, you may do:

template<typename C, C...cs> struct Chars
{
    using str_type = C[1 + sizeof...(cs)];
    static constexpr C str[1 + sizeof...(cs)] = {cs..., 0};

    constexpr operator const str_type&() const { return str; }
};

template<typename C, C...cs> constexpr C Chars<C, cs...>::str[1 + sizeof...(cs)];

// Requires GNU-extension
template <typename C, C...cs>
constexpr Chars<C, cs...> operator""_cs() { return {}; }

template <typename C, C...lhs, C...rhs>
constexpr Chars<C, lhs..., rhs...>
operator+(Chars<C, lhs...>, Chars<C, rhs...>) { return {}; }

With usage

constexpr auto hi = "Hello"_cs + " world\n"_cs;

std::cout << hi;

Demo

Without gnu extension, you have to use some MACRO to transform literal into char sequence, as I do there.

constexpr std::size_t length( const char * str ) {
  return (!str||!*str)?0:(1+length(str+1));
}

template<const char * String>
constexpr size_t len() { return length(String); }

extern constexpr const char HELLO[] = "Hello World!!!";

live example. Recursion wouldn't be needed in C++14.

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