本文介绍了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{}) {}
};
这篇关于C ++ 11:用另一个constexpr char数组初始化constexpr char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!