C++ Lambdas और C Closures
Lambda captures वाला unnamed callable बनाता है; C context explicitly पास करता है।
C++ Lambdas और C Closures क्या है?
Lambda captures वाला unnamed callable बनाता है; C context explicitly पास करता है।
Callback के लिए context capture करें।
महत्वपूर्ण बातें
- पहले C mechanism समझें।
- Ownership के लिए RAII और value semantics उपयोग करें।
- Macros और casts से अधिक type-safe abstractions चुनें।
C और C++ code examples
main.c
#include <stdio.h>
int above(int value, void *context) {
return value > *(int *)context;
}
int main(void) {
int values[] = {2, 7, 4, 9};
int threshold = 5;
int count = 0;
for (int index = 0; index < 4; ++index) {
count += above(values[index], &threshold);
}
printf("%d\n", count);
}
2
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector values{2, 7, 4, 9};
int threshold = 5;
auto above = [threshold](int value) {
return value > threshold;
};
std::cout << std::count_if(values.begin(), values.end(), above)
<< '\n';
}
2
C और C++ की तुलना
C function void* लेकर cast करता है; C++ lambda threshold को value से capture करके type information रखता है।
C
C prefixes, callbacks, macros और context structs उपयोग करता है।
C++
Language scoped और type-safe abstractions देता है।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- पहले C mechanism लिखें।
- Manual cleanup को RAII से बदलें।
- Allocation और virtual dispatch जाँचें।