为什么没有任何 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/