Modern C++ और C Alternatives

Templates और C Generic Techniques

Type-independent compile-time code लिखें।

Templates और C Generic Techniques क्या है?

Templates type-safe implementation generate करते हैं; C macros, void* या C11 _Generic उपयोग करता है।

महत्वपूर्ण बातें

  • पहले C mechanism समझें।
  • Ownership के लिए RAII और value semantics उपयोग करें।
  • Macros और casts से अधिक type-safe abstractions चुनें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int max_int(int left, int right) {
    return left > right ? left : right;
}

double max_double(double left, double right) {
    return left > right ? left : right;
}

#define MAX(left, right) _Generic((left), \
    int: max_int, double: max_double)((left), (right))

int main(void) {
    printf("%d %.1f\n", MAX(3, 9), MAX(2.5, 7.0));
}
अपेक्षित output
9 7.0
C++
कोड चलाएँ →
main.cpp
#include <iostream>

template<class T>
T maximum(const T& left, const T& right) {
    return left > right ? left : right;
}

int main() {
    std::cout << maximum(3, 9) << ' '
              << maximum(2.5, 7.0) << '\n';
}
अपेक्षित output
9 7

C और C++ की तुलना

_Generic supported types सूचीबद्ध करता है; C++ template required operations वाले हर type पर काम करता है।

C

C prefixes, callbacks, macros और context structs उपयोग करता है।

C++

Language scoped और type-safe abstractions देता है।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • पहले C mechanism लिखें।
  • Manual cleanup को RAII से बदलें।
  • Allocation और virtual dispatch जाँचें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज