Generic programming is implemented in C through templates and virtual functions. Function overloading uses templates to accept any type. Function overriding uses virtual template functions to provide a derived class's own implementation. Practical examples include using generic function overloading to find elements and using generic functions to override printing container elements.
Generic ProgrammingYes Refers to writing code that is independent of data types, thereby simplifying and reusing code. In C, we can implement generic programming by using templates and virtual functions.
Function overloadingAllows the creation of multiple functions with different parameter types using the same name. By using templates, we can make function overloads accept any type of parameters:
template <typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; }
Function overridingAllows derived classes to provide their own implementation of the parent class's virtual function. We can implement generic rewriting by using virtual template functions:
class Base { public: virtual void print() { std::cout << "Base class" << std::endl; } }; class Derived : public Base { public: virtual void print() override { std::cout << "Derived class" << std::endl; } };
Practical case
Using generic function overloading to find elements
template <typename T> bool find(std::vector<T>& vec, T value) { for (const auto& element : vec) { if (element == value) { return true; } } return false; } int main() { std::vector<int> int_vec = {1, 2, 3}; std::cout << std::boolalpha << find(int_vec, 2) << std::endl; // true std::vector<std::string> str_vec = {"Hello", "World"}; std::cout << std::boolalpha << find(str_vec, "World") << std::endl; // true }
Use generic functions to rewrite printing container elements
template <typename T> void print_container(std::vector<T>& vec) { for (const auto& element : vec) { std::cout << element << " "; } std::cout << std::endl; } int main() { std::vector<int> int_vec = {1, 2, 3}; print_container(int_vec); // 输出: 1 2 3 std::vector<std::string> str_vec = {"Hello", "World"}; print_container(str_vec); // 输出: Hello World }
The above is the detailed content of Application of generic programming in C++ function overloading and rewriting. For more information, please follow other related articles on the PHP Chinese website!