标准::比率背后的设计原则<>
Design principles behind std::ratio<>
我正在研究C++11标准中的类std::ratio<>
,该类允许进行编译时的有理算术。
我发现模板设计和用类实现的操作过于复杂,没有发现他们不能通过实现一个非常简单的rational类和为运算符定义constexpr
函数来使用更直接直观的方法的任何原因。结果会使类更易于使用,并且编译时的优势仍然存在。
与使用constexpr
的简单类实现相比,有人知道当前std::ratio<>
设计的优势吗?事实上,我找不到当前实现的任何优势。
当N2661被提出时,没有一个提案作者能够访问实现constexpr
的编译器。我们谁也不愿意提出一些我们无法构建和测试的东西。因此,constexpr
是否可以进行更好的设计甚至不是设计考虑的一部分。该设计仅基于作者当时可用的工具。
constexpr解决方案解决了完全不同的问题。创建std::ratio
是为了用作使用不同单位的变量之间的桥梁,而不是作为数学工具。在这种情况下,您绝对希望比率成为类型的一部分。constexpr解决方案在那里不起作用。例如,如果没有运行时空间和运行时成本,就不可能实现std::duration
,因为每个持续时间对象都需要在对象中携带其命名符/分母信息。
为操作员定义constexpr函数
您仍然可以在现有的std::ratio
:之上执行此操作
#include <ratio>
// Variable template so that we have a value
template<
std::intmax_t Num,
std::intmax_t Denom = 1
>
auto ratio_ = std::ratio<Num, Denom>{};
// Repeat for all the operators
template<
std::intmax_t A,
std::intmax_t B,
std::intmax_t C,
std::intmax_t D
>
constexpr typename std::ratio_add<std::ratio<A, B>, std::ratio<C, D>>::type
operator+(std::ratio<A, B>, std::ratio<C, D>) {}
// Printing operator
template<
std::intmax_t A,
std::intmax_t B
>
std::ostream &operator<<(std::ostream &os, std::ratio<A, B> r) {
return os << decltype(r)::num << "/" << decltype(r)::den;
}
#include <iostream>
int main() {
std::cout << ratio_<1,2> + ratio_<1,3> << std::endl;
return 0;
}
5/6
std::ratio
及其周围的机制将始终在编译时运行,这得益于模板元编程和类型操作。只有当C++设施需要常量表达式(例如模板参数或初始化constexpr
变量)时,constexpr
才需要在运行时运行。
那么,对你来说,编译时执行和"更直接、更直观"哪个更重要呢?
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中