c++ - 在编译时解析字符串

标签 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;
        }
    }

    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/

相关文章:

c++ - 在 `if constexpr` block 内声明的变量范围

c++ - 该代码在CodeSignal中工作不正确。不知道这是否是我的代码缺陷

c++ - 在 C++ 中,使用 bool 而不是 char 有什么意义?

c++ - std::variant 转换构造函数行为

c++ - 你可以有constexpr右值吗?

c++ - 不可调用对象的示例赋值运算符?

c++ - 将元素添加到未存储的 c++ 类中的 vector

c++ - Delphi 相当于 C++ 的 memset 是什么?

c++ - 使用 constexpr 编译时间哈希

c++ - set::vector 初始化用数字引号