Sunday, May 7, 2023

Templates types in C++ development:

C++ Templates 


Templates are a powerful feature in C++ that allows developers to write generic code that can work with different data types. Templates enable the creation of classes, functions, and data structures that can work with any data type, as long as that data type satisfies the requirements specified by the template.

Templates are defined using a syntax that includes the keyword "template" followed by a list of template parameters, enclosed in angle brackets. The template parameters can be data types, values, or other templates. For example, a template function that finds the maximum value in an array might be defined as follows:

```
template <typename T>
T findMax(T* arr, int size) 
{
    T maxVal = arr[0];
    for (int i = 1; i < size; ++i) 
    {
        if (arr[i] > maxVal) 
        {
            maxVal = arr[i];
        }
    }
    return maxVal;
}
```

In this example, the template parameter "T" specifies the data type of the array elements, which could be any valid data type in C++.

Templates are instantiated at compile time, which means that the compiler generates a separate copy of the template code for each data type that is used with the template. This can result in increased code size and compilation time, particularly for large templates or when many different data types are used with the template.

 

Template classes: 

A template class is a class that is parameterized by one or more data types. This allows the class to be used with different data types without needing to rewrite the class code for each data type. For example, a container class like `std::vector` can be defined as a template class to hold elements of any data type:

```

template <typename T>

class Vector 

{

    // Implementation here

};

```

example

#include <iostream>

template<typename T>

class MyVector {

private:

    T* m_data;

    size_t m_size;

public:

    MyVector(size_t size) : m_size(size) {

        m_data = new T[m_size];

    }

    ~MyVector() {

        delete[] m_data;

    }

    void set(size_t index, const T& value) {

        m_data[index] = value;

    }

    T& get(size_t index) {

        return m_data[index];

    }

    size_t size() const {

        return m_size;

    }

};


int main() {

    MyVector<int> intVec(5);

    for (size_t i = 0; i < intVec.size(); i++) {

        intVec.set(i, i * 2);

    }

    for (size_t i = 0; i < intVec.size(); i++) {

        std::cout << intVec.get(i) << " ";

    }

    std::cout << std::endl;


    MyVector<double> doubleVec(3);

    doubleVec.set(0, 1.23);

    doubleVec.set(1, 4.56);

    doubleVec.set(2, 7.89);


    for (size_t i = 0; i < doubleVec.size(); i++) {

        std::cout << doubleVec.get(i) << " ";

    }

    std::cout << std::endl;

    return 0;

}


Template functions: 

A template function is a function that is parameterized by one or more data types. This allows the function to be used with different data types without needing to rewrite the function code for each data type. For example, a function to find the maximum value in an array can be defined as a template function:

```

template <typename T>

T findMax(T* arr, int size) 

{

    T maxVal = arr[0];

    for (int i = 1; i < size; ++i) 

    {

        if (arr[i] > maxVal) 

        {

            maxVal = arr[i];

        }

    }

    return maxVal;

}

```

Template specialization: 

Template specialization is a technique that allows you to provide a different implementation for a template for a specific data type. For example, you might want to provide a specialized implementation of a container class like `std::vector` for a specific data type like `bool`:

```

template<>

class Vector<bool> 

{

    // Specialized implementation for bool type here

};

```

Template metaprogramming: 

Template metaprogramming is a technique that allows you to perform computations at compile time using templates. This can be used to generate code or perform complex calculations. For example, you might want to use template metaprogramming to compute the factorial of a number at compile time:

```

template <int N>

struct Factorial 

{

    static const int value = N * Factorial<N-1>::value;

};


template <>

struct Factorial<0> 

{

    static const int value = 1;

};

```

Variadic templates: 

Variadic templates allow you to create functions or classes that can take a variable number of arguments of any data type. This can be useful when you need to create functions or classes that can handle different numbers of arguments. For example, you might want to create a function that can print a variable number of arguments:

```

void printArgs() {}

template <typename T, typename... Args>

void printArgs(T arg, Args... args) 

{

    std::cout << arg << " ";

    printArgs(args...);

}

```

example code

#include <iostream>

template<typename... Args>

void print(Args... args) 

{

    std::cout << "Number of arguments: " << sizeof...(args) << std::endl;

    std::cout << "Arguments: ";

    (std::cout << ... << args) << std::endl;

}


int main() {

    print(1, 2, 3, "four", 5.0);

    return 0;

}


These are just a few examples of templates in C++ covering different areas. Templates are a powerful feature of the language that can help increase code reusability and flexibility. C++ developers should be familiar with the syntax and usage of templates and be able to use them effectively in their code.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...