Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ratio_equal ใน C++: เปรียบเทียบอัตราส่วนว่าเท่ากัน (Compile-time)

ratio_equal คืออะไร?

std::ratio_equal ใน <ratio> เป็น template ตรวจสอบว่า 2 ratio **เท่ากันทางคณิตศาสตร์** หรือไม่ (compile-time)

3/6 == 1/2 → true แม้ตัวเลขตัวเศษ/ตัวส่วนต่างกัน

Syntax

template <class R1, class R2> struct ratio_equal;

Static Member

  • value - true ถ้าเท่ากัน, false ถ้าไม่เท่ากัน

ตัวอย่าง

#include <iostream>
#include <ratio>
using namespace std;

int main() {
    typedef ratio<2, 5> R1;     // 0.4
    typedef ratio<10, 25> R2;   // 0.4
    typedef ratio<1, 3> R3;     // 0.333...
    typedef ratio<2, 5> R4;     // 0.4
    
    cout << "R1 == R2: " << ratio_equal<R1, R2>::value << "\n"; // 1 (true)
    cout << "R1 == R3: " << ratio_equal<R1, R3>::value << "\n"; // 0 (false)
    cout << "R1 == R4: " << ratio_equal<R1, R4>::value << "\n"; // 1 (true)
    
    // Denominator = 0 → compile error
    // typedef ratio<1, 0> R5; // static_assert failed: denominator cannot be zero
    
    return 0;
}

Output

R1 == R2: 1
R1 == R3: 0
R1 == R4: 1

Denominator = 0

พยายามสร้าง ratio<N, 0> จะได้ **compile-time error**:

static_assert(_Den != 0, "denominator cannot be zero");

Ratio Comparison Family

ratio_equal<R1,R2>           // ==
ratio_not_equal<R1,R2>       // !=
ratio_less<R1,R2>            // <
ratio_less_equal<R1,R2>      // <=
ratio_greater<R1,R2>         // >
ratio_greater_equal<R1,R2>   // >=

การประยุกต์: Compile-time Units

// ตัวอย่าง: ตรวจสอบหน่วยความเร็ว
using km_per_h = ratio<1000, 3600>;  // 1 km/h = 1000m/3600s
using m_per_s  = ratio<1, 1>;        // 1 m/s

static_assert(ratio_equal<km_per_h, ratio<5, 18>>::value, "1 km/h = 5/18 m/s");

สรุป

ratio_equal เปรียบเทียบอัตราส่วน compile-time อย่างปลอดภัย (ลดรูป GCD อัตโนมัติ) ใช้ใน template metaprogramming และ dimensional analysis