example3_partial_template_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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <type_traits>

template <typename T, typename U>
class Pair {
public:
    Pair(T first, U second) : first_(first), second_(second) {
        std::cout << "Generic Pair" << std::endl;
    }

    void display() {
        std::cout << "First: " << first_ << ", Second: " << second_ << std::endl;
    }

private:
    T first_;
    U second_;
};

template <typename T>
class Pair<T, T> {
public:
    Pair(T first, T second) : first_(first), second_(second) {
        std::cout << "Specialized Pair for same types" << std::endl;
    }

    void display() {
        std::cout << "Both: " << first_ << ", " << second_ << std::endl;
    }

private:
    T first_;
    T second_;
};

int main() {
    Pair<int, double> p1(1, 2.5);
    Pair<int, int> p2(3, 4);

    p1.display();
    p2.display();

    return 0;
}
Back to template_specialization