Home  >  Article  >  Backend Development  >  Comparison of C++ templates and generics?

Comparison of C++ templates and generics?

WBOY
WBOYOriginal
2024-06-04 16:24:12263browse

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?

Comparison of C++ templates and generics

Concept

  • Template: Code block defined at compile time, which can generate different codes according to specific data types.
  • Generics: An abstract interface where code can operate on different types of data, typed at runtime.

Difference

##FeatureTemplateGenericDefinition timingCompile timeRun timeTypedClearInferenceEfficiencyFasterSlowerCode sizeSmallerSmaller
##Practical case

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.14

Generic:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn