C ++ 11:用另一个constexpr char数组初始化constexpr char数组

C ++ 11:用另一个constexpr char数组初始化constexpr char数组

问题描述:

我想用另一个 constexpr char [] 成员初始化 constexpr char [] 成员.是否可以在 C ++ 11 或更高版本中进行?

I would like to initialize constexpr char[] member with another constexpr char [] member. Is it possible to do in C++11 or above?

#include <iostream>

struct Base {
 static constexpr char ValueOne[] = "One";
 static constexpr char ValueTwo[] = "Two";
};

template <typename T>
struct ValueOneHolder {
  static constexpr char Value[] = T::ValueOne; // << How can one initialize this?
};

int main() {
  std::cout << ValueOneHolder<Base>::Value << std::endl;
  return 0;
}

在此特定示例中,您可以将Value声明为以下内容:

In this particular example you may declare Value as the following:

template <typename T>
struct ValueOneHolder {
  static constexpr auto Value = T::ValueOne; // << How can one initialize this?
};

请注意,除非您切换到-std = c ++ 17或在源文件中添加以下行,否则GCC将无法链接此示例.

Please note, GCC will fail to link this example unless you switch to -std=c++17 or add the folloing lines in a source file.

constexpr char Base::ValueOne[];
constexpr char Base::ValueTwo[];

使用C ++ 14,还可以为constexpr字符串(或其子字符串)制作constexpr副本,如下例所示:

With C++14 it is also possible to make a constexpr copy of a constexpr string (or its substring), as shown in example below:

template<typename CharT, size_t Size>
struct basic_cestring {
    using value_type = CharT;
    template<size_t... I> constexpr
    basic_cestring(const char* str, index_sequence<I...>)
      : _data{str[I]...} {}
    inline constexpr operator const CharT* () const { return _data; }
    const CharT _data[Size + 1];
};

template<size_t Size>
struct cestring : public basic_cestring<char, Size>  {
    using index = make_index_sequence<Size>;
    constexpr cestring(const char* str)
    : basic_cestring<char, Size>(str, index{}) {}
};