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

ratio_not_equal ใน C++: เปรียบเทียบอัตราส่วนว่าไม่เท่ากัน

ratio_not_equal คืออะไร?

std::ratio_not_equal เป็น **compile-time template** ใน <ratio> เปรียบเทียบอัตราส่วน 2 ตัวว่า **ไม่เท่ากัน** (คือค่าทางคณิตศาสตร์ไม่เท่ากัน ไม่ใช่ตัวเลขตัวเศษ/ตัวส่วนเท่ากัน)

เช่น 3/6 และ 1/2 → **เท่ากัน** (ค่า = 0.5) → ratio_not_equal = false

Syntax

template <class R1, class R2> struct ratio_not_equal;

Static Member

  • value - true ถ้า R1 ≠ R2, false ถ้า R1 = R2
  • เป็น constexpr bool ใช้ใน compile-time ได้

ตัวอย่าง

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

int main() {
    typedef ratio<2, 5> R1;    // 2/5 = 0.4
    typedef ratio<1, 3> R2;    // 1/3 ≈ 0.333
    typedef ratio<3, 6> R3;    // 3/6 = 0.5
    typedef ratio<1, 2> R4;    // 1/2 = 0.5
    
    cout << "R1 vs R2: " << ratio_not_equal<R1, R2>::value << "\n"; // 1 (true)
    cout << "R3 vs R4: " << ratio_not_equal<R3, R4>::value << "\n"; // 0 (false)
    cout << "R1 vs R1: " << ratio_not_equal<R1, R1>::value << "\n"; // 0 (false)
    
    // ใช้ใน static_assert
    static_assert(ratio_not_equal<R1, R2>::value, "Ratios must differ");
    
    return 0;
}

Output

R1 vs R2: 1
R3 vs R4: 0
R1 vs R1: 0

ฟังก์ชัน ratio เปรียบเทียบอื่นๆ

การทำงานภายใน

C++ ลดรูปอัตราส่วน (divide by GCD) แล้วเปรียบเทียบ numerator และ denominator แยกกัน
→ ไม่มี overflow เพราะคำนวณที่ compile-time ด้วย integer arithmetic

Use Cases

  • Compile-time dimensional analysis (units)
  • Template metaprogramming เงื่อนไข branching
  • Static assertions ตรวจสอบหน่วย/อัตราส่วน

สรุป

ratio_not_equal<R1,R2>::value ตรวจสอบว่า 2 ratio ไม่เท่ากันทางคณิตศาสตร์ (compile-time) ใช้ร่วมกับ ratio family อื่นๆ

Templateความหมาย
ratio_equal<R1,R2>R1 == R2
ratio_not_equal<R1,R2>R1 != R2
ratio_less<R1,R2>R1 < R2
ratio_less_equal<R1,R2>R1 ≤ R2
ratio_greater<R1,R2>R1 > R2
ratio_greater_equal<R1,R2>R1 ≥ R2