example3_class_template.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
#include <iostream>

// Define a class template
template<typename T>
class Box {
private:
    T value;
public:
    Box(T val) : value(val) {}

    T getValue() const {
        return value;
    }
};

int main() {
    Box<int> intBox(123);
    Box<double> doubleBox(45.67);

    // Access the value stored in the boxes
    std::cout << "Integer Box: " << intBox.getValue() << std::endl;
    std::cout << "Double Box: " << doubleBox.getValue() << std::endl;

    return 0;
}
Back to templates