Home > Article > Backend Development > Comparison of C++ templates and generics?
The difference between templates and generics in C++: Templates: defined at compile time, clearly typed, high efficiency, and small code size. Generics: runtime typing, abstract interface, provides flexibility, low efficiency.
Comparison of C++ templates and generics
Concept
Difference
Template | Generic | |
---|---|---|
Compile time | Run time | |
Clear | Inference | |
Faster | Slower | |
Smaller | Smaller |
Template:
template<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
This template function can calculate the maximum value of different types of data, for example:
int max_int = max(10, 20); // 输出:20 double max_double = max(3.14, 2.71); // 输出:3.14Generic:
class NumberComparator {
public:
bool operator()(int a, int b) const {
return a < b;
}
};
This generic class implements an interface for comparing integers and can be used for different sorting algorithms:
std::vector<int> numbers = {5, 2, 8, 3, 1}; std::sort(numbers.begin(), numbers.end(), NumberComparator()); for (auto& number : numbers) { std::cout << number << " "; // 输出:1 2 3 5 8 }Conclusion
Templates and generics are powerful C++ features, Code for handling different data types. Templates are typed at compile time, making them more efficient and smaller in code size. Generics perform type inference at runtime and provide a more abstract interface, but are slightly less efficient.
The above is the detailed content of Comparison of C++ templates and generics?. For more information, please follow other related articles on the PHP Chinese website!