繁体   English   中英

std :: ratio <>背后的设计原则

[英]Design principles behind std::ratio<>

我正在查看C ++ 11标准中的类std::ratio<> ,该标准允许进行编译时合理算术。

我发现模板设计和用类实现的操作过于复杂,并且没有找到任何理由为什么他们不能通过实现一个非常简单的合理类并为运算符定义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才需要在运行时运行。

那对哪个更重要:编译时执行,还是“更直接,更直观”?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM