Chuyển đến nội dung chính
eLearner.app
Mô-đun 8 · Bài học 2 trong tổng số 218/18 trong khóa học~15 min
Bài học theo mô-đun (2/2)

Mẫu lớp học

Just like functions, classes can also be parameterized with respect to one or more data types. This allows us to define generic data structures (such as lists, queues, stacks, or wrappers) that work with any data type without duplicating code.

Defining a Class Template

To declare a class template, we use the template <typename T> syntax immediately before the class definition. Inside the class, we can use the type parameter T to define member variables, return types, or member function parameters.

Code
template <typename T>
class Box {
private:
    T value;
public:
    Box(T v) : value(v) {}

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

Instantiation

When creating an object of a class template, we must explicitly specify the type between angle brackets <> (although starting with C++17, the compiler can deduce it in some contexts via Class Template Argument Deduction or CTAD):

Code
Box<int> intBox(10);        // T becomes int
Box<double> doubleBox(3.14); // T becomes double

Template Specialization

Sometimes we want a different behavior for a class template when it is instantiated with a specific type. In this case, we define a total specialization using the template <> syntax followed by the class definition specifying the target type:

Code
// Total specialization for the bool type
template <>
class Box<bool> {
private:
    bool value;
public:
    Box(bool v) : value(v) {}

    void printState() {
        std::cout << (value ? "True" : "False");
    }
};

Try it yourself

tập thể dục#cpp.m8.l2.e1
Nỗ lực: 0Đang tải…

Declare a class template named Box that contains a private member named value of type T, a constructor that initializes it, and a public method getValue() const that returns the value.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Remember to prepend `template <typename T>` to the `Box` class declaration.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#cpp.m8.l2.e2
Nỗ lực: 0Đang tải…

Declare a class template Wrapper<T> with a public member data of type T, a constructor Wrapper(T d), and a print() method that prints data to std::cout. Next, create a total specialization for Wrapper<char> where the print() method prints the character enclosed in single quotes (e.g., 'A' instead of A).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `template <>` to indicate the total specialization of `Wrapper<char>`.

Giải pháp khả dụng sau 3 lần thử