c++ - 强制表达式为 constexpr

标签 c++ c++17 variadic-templates template-meta-programming constexpr

给定两个 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;
}

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

最佳答案

问题是 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;
}

但是如果你只有 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 {}; }

关于c++ - 强制表达式为 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723272/

相关文章:

c++ - 如何在C++中将文件夹从一个路径复制到另一个路径

c++ - 连接 Boost Hana 字符串

c++ - 结构的通用比较运算符

c++ - 子类的动态方法在 lambda 捕获中使用时调用父类的虚方法/导致段错误

c++ - 嵌套的 for_each 循环导致 vector 大小意外增加

java - C 和 C++ 中的 JNI 调用不同?

c++ - 没有连接如何调用slot?

c++ - 重载可变长度模板函数的递归结束

具有函数参数评估的 C++17 参数包扩展

c++ - 绑定(bind)返回值和可变参数模板