C++ Template inheritance allows template-derived classes to reuse the code and functionality of the base class template, which is suitable for creating classes with the same core logic but different specific behaviors. The template inheritance syntax is: template
C++ Template Inheritance
Template inheritance allows you to reuse the code and functionality of a base class template in a derived class. This is useful for creating classes that share the same core logic but have different specific behaviors.
Syntax
template<typename T> class Base { // 基类模板代码 }; template<typename T> class Derived : public Base<T> { // 派生类模板代码 };
Example
Suppose we have the following Base
template class, which implements Simple Counter:
template<typename T> class Base { public: Base() : count(0) {} void increment() { ++count; } T getCount() const { return count; } private: T count; };
Now, we want to create a Derived
class that inherits the counting functionality of Base
but also adds an additional method to print the current count :
template<typename T> class Derived : public Base<T> { public: void printCount() const { cout << "Count: " << getCount() << endl; } };
Practical case
The following is a practical case using C++ template inheritance:
#include <iostream> int main() { Derived<int> counter; counter.increment(); counter.increment(); counter.printCount(); // 输出: Count: 2 return 0; }
In this example, we create a C++ template Inherited Derived
class instance, which provides the counting function of the Base
class, and adds the printCount
method to print the current count.
The above is the detailed content of How to use C++ template inheritance?. For more information, please follow other related articles on the PHP Chinese website!