StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Tuesday, May 27, 2008

C++ Templates

 May 27, 2008     CPP     No comments   

What are templates?

  • Templates provide a mechanism to handle different data types in the same function or class.
  • When used in functions they are referred as function templates.
  • When used with classes they are referred as class templates.
  • Template arguments are specified either with keywords "class" or "typename".
  • Main advantages of templates are that they make the code listing smaller and maintenance burden is reduced since changes are done at one place only.

Demonstrate the usage of function templates

#include <iostream>
using namespace std;

// Template function
template <typename T>
T max ( T a, T b ) {
    return a<b?b:a;
}

// Overloaded
template <typename T>
T max ( T a, T b, T c ) {
    return max(max(a,b),c);
}

// Args of different types
template <typename T, typename S>
void func ( T a, S b ) {
    cout << a << " " << b << endl;
}

void main()
{
    // Call to 2 arg template function
    cout << max(1,2) << endl;
    cout << max<int>(1,2) << endl;
    cout << max(1.1,2.1) << endl;
    cout << max<double>(1,2.1) << endl;
    cout << max(static_cast<double>(1),2.1) << endl;
    cout << max("hello", "world") << endl;

    /* Compilation error when different types are used
      cout << max(1, 1.2) << endl;
      Error E2285 template.cpp 26: Could not find a match for 'max<_T>(int,double)' in function main()
     */

    // Call to overloaded template function
    cout << max(1,2,3) << endl;

    // Call to template function with different arg types
    func(1, 1.2);
}
OUTPUT:
2
2
2.1
2.1
2.1
world
3
1 1.2

Demonstrate the usage of class templates

#include lt;iostreamgt;
#include lt;vectorgt;
#include lt;stdexceptgt;
using namespace std;

template <typename T>
class MyClass {
    vector<T> data;

  public:
    void Add(T& a) {
        data.push_back(a);
    }

    T Get() {
        if ( data.empty() )
        {
           throw out_of_range("Out of range");
        }
        return data.back();
    }
};

void main()
{
    // Class used with int
    int val1 = 100, val2 = 200;
    MyClass<int> intObj;
    intObj.Add(val1);
    intObj.Add(val2);
    cout << intObj.Get() << endl;

    // Class used with string
    string str1 = "Hello", str2 = "World";
    MyClass<string> strObj;
    strObj.Add(str1);
    strObj.Add(str2);
    cout << strObj.Get() << endl;
}
OUTPUT:
200
World
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk