c++ - 为什么 std::algorithms 不是 constexpr 可能是?

标签 c++ algorithm c++14 constexpr

为什么没有任何 std::algorithm 方法 constexpr?如果我正确理解新的 C++14 规则,其中许多方法可能是 constexpr。比如为什么std::find不能是constexpr

static constexpr std::array<char, 4> DnaBases {'A', 'C', 'G', 'T'};

constexpr bool is_dna(char b)
{
    return std::find(std::cbegin(DnaBases), std::cend(DnaBases), b) != std::cend(DnaBases); // why not?
}

还有哪些std::algorithm可以是constexpr

最佳答案

它可以是 constexpr,但不能作为常量表达式求值,因为在这种情况下,例如编译时 find 需要: begin/end 应该是 constexpr,迭代器的 * operator 应该是 constexpr,operator == 应该是 constexpr,operator ! = 的迭代器应该是 constexpr,operator++ 的迭代器应该是 constexpr。但是,如果所有的函数都是constexpr,那么很多算法都可以用constexpr来实现。

您可以查看SPROUT library用于实现 constexpr 容器/算法。

以及在 isocpp.org forums 上的相关讨论

关于c++ - 为什么 std::algorithms 不是 constexpr 可能是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395408/

相关文章:

c++ - 仿函数/函数对象的 is_function 类型特征

algorithm - 高效求解稀疏矩阵

c++11/14 make_unique std::string 的模糊重载

c++ - 模板化构造函数中模板参数的数量

c++ - std::is_constructible 没有给出正确的结果

c++ - 为什么我得到未引用的局部变量

c++ - 库的子进程的进程组

c++ - new分配了多少字节?

c - 仅使用数组的链表实现

algorithm - 预测室内温度的机器学习算法