مرکزی مواد پر جائیں
eLearner.app
ماڈیول 8 · سبق 2 از 2کورس میں 18/18~15 min
ماڈیول اسباق (2/2)

کلاس ٹیمپلیٹس

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

ورزش#cpp.m8.l2.e1
کوششیں: 0لوڈ ہو رہا ہے…

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.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

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

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#cpp.m8.l2.e2
کوششیں: 0لوڈ ہو رہا ہے…

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).

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

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

3 کوششوں کے بعد حل دستیاب ہے۔