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
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

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

Popular Posts

  • 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 ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • 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...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk