我正在研究C++11标准中的std::ratio<>类,它允许在编译时进行有理运算。
我发现模板设计和使用类实现的操作过于复杂,并且没有找到任何理由,为什么他们不能通过实现一个非常简单的rational类并为操作符定义constexpr函数来使用更直接和直观的方法。结果将是一个更容易使用的类,并且编译时的优势将保持不变。
有人知道与使用constexpr的简单类实现相比,当前的std::ratio<>设计有什么优势吗?实际上,我找不到当前实现的任何优势。
发布于 2012-09-08 06:22:01
当N2661被提出时,没有一个提案的作者能够访问实现constexpr的编译器。我们没有人愿意提出一些我们无法构建和测试的东西。因此,是否可以用constexpr完成更好的设计甚至不是设计考虑的一部分。该设计仅基于作者当时可用的工具。
发布于 2012-09-08 07:25:52
constexpr解决方案解决了完全不同的问题。创建std::ratio的目的是作为使用不同单位的变量之间的桥梁,而不是作为数学工具。在这些情况下,您绝对必须希望比率成为类型的一部分。constexpr解决方案在那里不起作用。例如,如果没有运行时空间和运行时成本,就不可能实现std::duration,因为每个持续时间对象都需要在对象中携带其命名符/分母信息。
发布于 2018-06-09 06:06:03
为运算符定义常量表达式函数
您仍然可以在现有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/6https://stackoverflow.com/questions/12325741
复制相似问题