C++ 在编译时解析字符串
我正在尝试编译以下代码:C++ 在编译时解析字符串,c++,c++17,C++,C++17,我正在尝试编译以下代码: #include <string_view> constexpr size_t get_member_count(const char * va) { const char * p = va; size_t count = 1; while (*p != 0) { if (*p++ == ',') { ++count; } }
#include <string_view>
constexpr size_t get_member_count(const char * va)
{
const char * p = va;
size_t count = 1;
while (*p != 0)
{
if (*p++ == ',')
{
++count;
}
}
return count;
}
template <const char * va>
constexpr auto get_member_names()
{
constexpr size_t count = get_member_count(va);
static std::basic_string_view<char> v[count];
//fill the array here
return v;
}
int main()
{
constexpr const char * mem_list = "a, b, c";
constexpr auto v = get_member_names<mem_list>();
}
发件人:
对于引用或指针类型的非类型模板参数,或者对于类类型的非类型模板参数或其子对象中的引用或指针类型的每个非静态数据成员,引用或指针值不应引用或是(分别)的地址:
- [……]
- 字符串文字([lex.string])
- [……]
constexpr const char*mem_list=“a,b,c”;
constexpr auto v=get_member_names();
不行。您必须创建一个静态存储持续时间数组。像这样:
static const char mem_list[] = "a, b, c";
constexpr auto v = get_member_names<mem_list>();
static const char mem_list[]=“a,b,c”;
constexpr auto v=get_member_names();
constexpr const char * mem_list = "a, b, c";
constexpr auto v = get_member_names<mem_list>();
static const char mem_list[] = "a, b, c";
constexpr auto v = get_member_names<mem_list>();