强制将表达式表达为constexpr

Rly*_*yeh 2 c++ template-meta-programming variadic-templates constexpr c++17

给定两个constexpr功能,是否可以将它们组合为一个功能?

template <char... C>
constexpr int boo()
{
    char ch[] = { C... };
    int count = 0;

    for (char c : ch)
    {
        if (c != '0') count += 1;
    }

    return count;
}

template <char... C>
constexpr auto foo()
{
    std::array<char, boo<C...>()> x{};

    return x;
}
Run Code Online (Sandbox Code Playgroud)

如示例所示,我可以将' count'作为常量返回。我的问题是我不能count在声明的函数中使用' '作为常量。也就是说,如果将' boo()' 的主体放在' foo()'中,则编译器将抛出' count'不是常量。

max*_*x66 5

问题是std::array需要一个恒定的大小值。

如果您在中定义count和修改它foo()count(如在foo()函数中看到的)是变量,而不是常量。

因此,您需要在另一个位置进行修改:在constexpr函数中,以便返回的值成为编译时已知的常量。

如果你可以使用C ++ 17,所以模板折叠(与EVG和Rakete1111改善;感谢),你能避免bar()在所有

template <char... C>
constexpr auto foo()
{
    std::array<char, (0u + ... + (C != '0'))> x{};

    return x;
}
Run Code Online (Sandbox Code Playgroud)

但是如果只有C ++ 11,则需要递归

template <typename = void>
constexpr std::size_t bar ()
 { return 0u; }

template <char C0, char ... C>
constexpr std::size_t bar ()
 { return bar<C...>() + (C0 == '0' ? 0u : 1u); }

template <char... C>
constexpr std::array<char, bar<C...>()> foo()
 { return {}; }
Run Code Online (Sandbox Code Playgroud)

  • 我会使用`0 + ... +`作为通用性。参数pack可以为空,并且std :: array的大小可以为零。 (4认同)