DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

variadic templates c++11

Please check the normal templates first.

Variadic Templates

This is a special type of template that allows any number of any category type as parameters in template. Example:

template<typename... Ts>
void myprintf(Ts... args)
{std::cout<<"size:"<<sizeof...(Ts)<<std::endl;}

source code with example:

/*
Program: Variadic Templates 
Author: Alpha Master
Date: 13 March 2021
*/

//Header File
#include<iostream>

//Function to print last element
template<typename T>
void myprintf(T value) 
{
    std::cout <<"Last Element:"<< value << std::endl;
}

//Function to print all element except last element
template<typename T, typename... Ts>
void myprintf(T value, Ts... args) 
{
    std::cout << "Element:"<<value << std::endl;
    myprintf(args...);
}

int main()
{
    std::cout<<"Variadic Templates"<<std::endl;
    myprintf(5, 10, "alpha", 3.3, "var");
    return 0;
}

Output:

Variadic Templates
Element:5
Element:10
Element:alpha
Element:3.3
Last Element:var

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer