example6_class_template_partial_specialization.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

// Generic template
template<typename T, typename U>
class MyClass {
public:
    void show() {
        std::cout << "Generic MyClass" << std::endl;
    }
};

// Partial specialization for T = int
template<typename U>
class MyClass<int, U> {
public:
    void show() {
        std::cout << "Specialized MyClass for int" << std::endl;
    }
};

int main() {
    MyClass<double, double> obj1;
    obj1.show();  // Outputs: Generic MyClass

    MyClass<int, double> obj2;
    obj2.show();  // Outputs: Specialized MyClass for int

    return 0;
}
Back to templates