为什么没有任何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?
}
Run Code Online (Sandbox Code Playgroud)
还有哪些std::algorithm可能constexpr?
考虑一个简单的INT Wrapper与重载乘法类operator*=和operator*.对于"旧式"运算符重载,可以定义operator*,operator*=甚至还有像Boost.Operators这样的库以及@DanielFrey的现代化版本操作符,它们可以为您减少样板.
但是,对于使用新C++ 11的编译时计算constexpr,这种便利性消失了.A constexpr operator*无法调用,operator*=因为后者修改了它的(隐式)左参数.此外,constexpr没有过载,因此constexpr operator*在现有operator*结果中添加额外的过载分辨率模糊.
我目前的做法是:
#include <iostream>
struct Wrap
{
int value;
Wrap& operator*=(Wrap const& rhs)
{ value *= rhs.value; return *this; }
// need to comment this function because of overloading ambiguity with the constexpr version
// friend Wrap operator*(Wrap const& lhs, Wrap const& rhs)
// { return Wrap { …Run Code Online (Sandbox Code Playgroud) 这是我之前提出的问题的后续问题"C++ 14标准库的哪些部分可能是什么以及将制作哪些部分constexpr?" 和" constexpr运营商超载指南?"
在运行时世界中,为多个数据成员的结构重载的operator<一个很好的习惯用法是std::tie将结构转换为a std::tuple并在其上进行捎带,operator<这就是Right Thing™(各种成员的字典比较).
在C++ 14,许多地方std::tuple制成constexpr,特别是make_tuple,std::get与前面提到的operator<.然而,似乎看似相关std::tie的没有标记constexpr.这很烦人,因为它使定义用户定义的文字类型在编译时可以比必要的更冗长.
问题:是否有任何技术原因std::tie未标记constexpr为C++ 14?
更新:LWG问题2301,在libc ++和libstdc ++ bug 65978中实现
更新2:在修改libstdc ++错误报告后,由@JonathanWakely修复了3个多小时!
将代码转换为什么的一般提示是constexpr什么?比方说,有一种算法可以对(输入)几何图形进行几何变换.输入和输出因性质和大小而不同,并且非常简单地相互依赖.目前它实现为一个类,目前使用std::map和std::vector(不失一般性).
什么是重构代码的方法,它使用动态内存来获取符合常量表达式要求的代码?
对于每个使用的constexpr容器,我可以想象一些兼容的容器和constexpr兼容的"堆栈分配器"(用于足够大的存储)的组合value_type.但是有一个问题:我从未遇到过这样的容器.但也许还有另外一种方法?
所以说我想制作一些constexpr仿函数,虽然我可以使用它bind.有什么我想念的吗?为什么不能bind退货constexpr?
鉴于:
struct foo {
int b() const { return _b; }
int a() const { return _a; }
int r() const { return _r; }
const int _b;
const int _a;
const int _r;
};
Run Code Online (Sandbox Code Playgroud)
我想要:
constexpr auto sumB = bind(plus<int>(), placeholders::_1, bind(&foo::b, placeholders::_2));
constexpr auto sumA = bind(plus<int>(), placeholders::_1, bind(&foo::a, placeholders::_2));
constexpr auto sumR = bind(plus<int>(), placeholders::_1, bind(&foo::r, placeholders::_2));
Run Code Online (Sandbox Code Playgroud)
有什么我可以做的工作吗?