我正在尝试编译以下代码:
#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>();
}
MSVC 2017 和 GCC 9 都不会编译“get_member_names()”,分别告诉“找不到匹配的重载函数”或“没有匹配的调用函数”。
函数 get_member_count 可以编译,我可以这样做:
constexpr size_t mem_count = get_member_count(mem_list);
最佳答案
来自 [temp.arg.nontype]/2 :
For a non-type template-parameter of reference or pointer type, or for each non-static data member of reference or pointer type in a non-type template-parameter of class type or subobject thereof, the reference or pointer value shall not refer to or be the address of (respectively):
- [...]
- a string literal ([lex.string]),
- [...]
所以这样:
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>();
关于c++ - 在编译时解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54713443/