标准::比率背后的设计原则<>

Design principles behind std::ratio<>

本文关键字:lt gt 原则 比率 背后 标准      更新时间:2023-10-16

我正在研究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才需要在运行时运行。

那么,对你来说,编译时执行和"更直接、更直观"哪个更重要呢?