Home >Backend Development >C++ >How to use C++ template inheritance?

How to use C++ template inheritance?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2024-06-06 10:33:17854browse

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 class Derived : public Base { }. Example: template class Base { }; template class Derived : public Base { };. Practical case: Created the derived class Derived, inherited the counting function of the base class Base, and added the printCount method to print the current count.

How to use C++ template inheritance?

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!

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