一 簡介
頭文件<ratio>
template< std::intmax_t Num, std::intmax_t Denom = 1 >
class ratio; (since C++11)
1. std::ratio 支持編譯期的有理數運算。
2. 當 Num 和 Denom 是編譯期的std::intmax_t的常量時,該模板的每個實例都精確表示某個有限有理數。
3. 只要 Num 和 Denom 不同,即使化簡後表示的有理數相同,兩個std::ratio也不是相同的類型.
two
std::ratio
with differentNum
orDenom
are distinct types even if they represent the same rational number (after reduction).
4. std::ratio 的成員 type表示的是該std::ratio的最簡類型(lowest terms)。例如 std::ratio<2, 4>::type是std::ratio<1, 2> 。
二 輔助函數
std::ratio有一些用於算術運算和邏輯運算的輔助函數。
1. 算術運算
ratio_add
ratio_subtract
ratio_multiply
ratio_divide
它們的返回類型還是std::ratio。
2. 邏輯運算
ratio_equal
ratio_not_equal
ratio_less
ratio_less_equal
ratio_greater
ratio_greater_equal
它們通過value返回 std::true_type 或 std::false_type。
三 例子
#include <iostream>
#include <type_traits> // is_same
#include <ratio>
int main() {
// 類型比較及type成員
std::cout << std::boolalpha << std::is_same<std::ratio<10,20>, std::ratio<100,200>>()
<< std::endl;
std::cout << typeid(std::ratio<10, 20>::type).name() << std::endl;
std::cout << typeid(std::ratio<100, 200>::type).name() << std::endl;
// 靜態數據成員
std::cout << std::ratio<100, 200>::num << std::endl;
std::cout << std::ratio<100, 200>::den << std::endl;
// 算術運算
using r = std::ratio_add<std::ratio<10,20>, std::ratio<100,200>>;
std::cout << r::num << std::endl;
std::cout << r::den << std::endl;
// 邏輯運算
std::cout << std::ratio_equal<std::ratio<10,20>, std::ratio<100,200>>::value << std::endl;
std::cin.get();
return 0;
}
結果:
四 相關常量類型
爲了方便使用,<ratio>中定義了一些常量類型,如下:
yocto std::ratio<1, 1000000000000000000000000>, if std::intmax_t can represent the denominator
zepto std::ratio<1, 1000000000000000000000>, if std::intmax_t can represent the denominator
atto std::ratio<1, 1000000000000000000>
femto std::ratio<1, 1000000000000000>
pico std::ratio<1, 1000000000000>
nano std::ratio<1, 1000000000>
micro std::ratio<1, 1000000>
milli std::ratio<1, 1000>
centi std::ratio<1, 100>
deci std::ratio<1, 10>
deca std::ratio<10, 1>
hecto std::ratio<100, 1>
kilo std::ratio<1000, 1>
mega std::ratio<1000000, 1>
giga std::ratio<1000000000, 1>
tera std::ratio<1000000000000, 1>
peta std::ratio<1000000000000000, 1>
exa std::ratio<1000000000000000000, 1>
zetta std::ratio<1000000000000000000000, 1>, if std::intmax_t can represent the numerator
yotta std::ratio<1000000000000000000000000, 1>, if std::intmax_t can represent the numerator
五 參考