SlideShare a Scribd company logo
Arindam Mukherjee 
Pune C++ and Boost Meetup 
C++TEMPLATE METAPROGRAMMING
Template type computations 
 Templates provide a Turing complete 
computation subsystem – that runs during 
compilation. 
 This capability was not entirely consciously 
designed. 
 Erwin Unruh found this somewhat 
accidentally ~ early 90s.
Templates 
 Compile time entities completely evaluated 
by the compiler, based on arguments passed. 
std::vector<int> nums; // std::vector<int> unrelated 
std::vector<std::string> names; // to std::vector<std::string> 
template <typenameT> class Foo; // declaration 
template <typenameT> class Foo { … }; // definition 
Foo<int> foonum; // Foo<int> is specialization
Non-type template parameters 
 Templates can have non-type parameters: 
template <typename T, int N> 
struct array { 
T data[N]; 
…. 
} 
 Non-type args are compile time constants. 
array<int, 10> arr; // array of 10 ints 
 sizeof is evaluated at compile time. 
int arr[sizeof(int)]; // array of 4* ints
Embedded types 
 Typedefs inside a class / class template. 
template <typename T> 
struct add_const { 
typedef const T type; 
}; 
add_const<int>::type ci; // const int
Embedded constants 
 Enums inside a class / class template. 
template <int M, int N> struct add { 
enum { value = M + N } 
} 
int array[add<10, 20>::value];
Branching: specializations 
 Specialize for specific types. 
template <typename T> 
struct Foo { … }; // default impl 
template <> 
struct Foo<int> { … }; // int-specific 
 Applicable to function templates too.
Partial specializations 
 Specialize for type families. 
template <typename T, typename U> 
struct Foo { … }; // default impl 
template <typename T> 
struct Foo<T, T> { … }; // Foo<char, char> 
template <typename T> 
struct Foo<T*, T> { … }; // Foo<int*, int> 
 NOT applicable to function templates.
Recursion by specializations 
 Compute factorial at compile time: 
template <int N> struct factorial { 
enum { value = N*factorial<N-1>::value }; 
}; 
template <> struct factorial<0> { // 
terminating condition 
enum { value = 1 }; 
};
Applying the techniques 
 Remove const: 
template <typename T> struct remove_const 
{ typedef T type; }; 
template <typename T> // partial 
struct remove_const<const T> { // speclzn 
typedef T type; 
}; 
 Called as: 
remove_const<const int>::type x; // int
Applying the techniques 
 Querying types: 
template <typename T, typename U> 
struct are_same 
{ enum { value = 0 }; }; 
template <typename T> / partial 
struct are_same<T, T> // specialization 
{ enum { value = 1 }; }; 
 Called as: 
are_same<int, int>::value == 1;
Applying the techniques 
 Remove levels of indirection: 
template <typename T> 
struct deref 
{ typedef T type; }; 
template <typename T> // partial 
struct deref<T*> { // specialization 
typedef typename deref<T>::type type; 
} 
 Called as: 
deref<int*****>::type x; // x is int
Boost Type Traits 
 A header-only library to query and 
manipulate types at compile time. 
 Lots of trait metafunctions. 
#include <boost/type_traits.hpp> 
typedef int* intptr; 
assert(boost::is_ptr<intptr>::value); 
struct Foo {int a; void *b; float c; }; 
assert(boost::is_pod<Foo>::value);
SFINAE 
 Compiler tries to resolve function calls to a 
unique overload, or unique template with 
appropriate arguments. 
 Multiple templates may be candidates but a 
unique one must survive. 
 All candidates instantiated. 
 Those that fail instantiation eliminated. Not 
An Error if a single candidate survives.
SFINAE & enable_if 
 Exploit SFINAE to resolve to apt template. 
 boost::enable_if 
#include <boost/utility/enable_if.hpp> 
boost::enable_if<true, T>::type x; // T 
boost::enable_if<false, T>::type y; //!def 
 boost::disable_if (opposite of enable_if).
SFINAE & enable_if (contd.) 
 Serialize arbitrary types: 
#include <boost/utility/enable_if.hpp> 
typedef vector<char> buffer_t; 
template <typename T> 
buffer_t serialize(const T&); 
 Need a fast version for POD types and 
generic version for non-POD types. 
template <typename T> 
enable_if<is_pod<T>, vector<char>>::type 
serialize(const T&) {…} // pod version 
// Use disable_if for the non-POD version
Metafunctions 
 Metafunction: a class or class template taking 
only type parameters, with a single 
embedded typedef. 
 All the Boost type traits are metafunctions. 
 Boost TMP Library: library of metafunctions. 
 Provides means of composing and generating 
metafunctions from simpler metafunctions.
Boost TMP Library 
 Metafunctions need to be combined: 
#include <boost/type_traits.hpp> 
template <typename T> void foo(T obj) { 
if (boost::is_pointer<T>::value || 
boost::is_array<T>::value) 
{ … } 
else { … } 
}
Boost TMP Library (contd.) 
 How to make another metafunction that OR’s 
two type traits. 
#include <boost/mpl/or.hpp> 
#include <boost/type_traits.hpp> 
template <typename T> void foo(T obj) { 
if (boost::mpl::or_< 
boost::is_pointer<T>::value 
, boost::is_array<T>::value 
>::value) 
{ … } 
else { … } 
}
Boost TMP Library (contd.) 
 Numbers can be wrapped in types: 
#include <boost/mpl/integral_c.hpp> 
#include <boost/mpl/greater.hpp> 
#include <boost/type_traits.hpp> 
namespace mpl = boost::mpl; 
template <typename T, typename U> 
struct is_larger : mpl::greater< 
mpl::integral_c<size_t, sizeof T> 
, mpl::integral_c<size_t, sizeof U> 
> 
{};
Thank you! 
 Q & A 
 Book: Modern C++ Design – Andrei 
Alexandrescu 
 Book: Advanced C++ Template 
Metaprogramming – Davide di Gennaro 
 Book: C++ Template Metaprogramming – 
Dave Abrahams, Aleksey Gurtovoy

More Related Content

What's hot

Iterator protocol
Iterator protocolIterator protocol
Iterator protocol
Akshar Raaj
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
Sudheer Kiran
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Rai University
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta ProgrammingReggie Meisler
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
Appili Vamsi Krishna
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
Claus Wu
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppteShikshak
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
Vijayananda Ratnam Ch
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
Mohammed Saleh
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
02basics
02basics02basics
02basics
Waheed Warraich
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
SANDIP MORADIYA
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
Nico Ludwig
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
rgnikate
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in c
Rahul Budholiya
 

What's hot (20)

Iterator protocol
Iterator protocolIterator protocol
Iterator protocol
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
02basics
02basics02basics
02basics
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Modern C++
Modern C++Modern C++
Modern C++
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in c
 
Functions in C
Functions in CFunctions in C
Functions in C
 

Viewers also liked

C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013
Ratsietsi Mokete
 
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
Dominic Suciu
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
Sławomir Zborowski
 
C++ scalable network_io
C++ scalable network_ioC++ scalable network_io
C++ scalable network_io
Arindam Mukherjee
 
Knime &amp; bioinformatics
Knime &amp; bioinformaticsKnime &amp; bioinformatics
Knime &amp; bioinformatics
BioinformaticsInstitute
 
2015 ohsu-metagenome
2015 ohsu-metagenome2015 ohsu-metagenome
2015 ohsu-metagenome
c.titus.brown
 
2015 pag-metagenome
2015 pag-metagenome2015 pag-metagenome
2015 pag-metagenome
c.titus.brown
 

Viewers also liked (7)

C++ tutorial boost – 2013
C++ tutorial   boost – 2013C++ tutorial   boost – 2013
C++ tutorial boost – 2013
 
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
Interactive Analysis of Large-Scale Sequencing Genomics Data Sets using a Rea...
 
Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17Metaprogramming in C++ - from 70's to C++17
Metaprogramming in C++ - from 70's to C++17
 
C++ scalable network_io
C++ scalable network_ioC++ scalable network_io
C++ scalable network_io
 
Knime &amp; bioinformatics
Knime &amp; bioinformaticsKnime &amp; bioinformatics
Knime &amp; bioinformatics
 
2015 ohsu-metagenome
2015 ohsu-metagenome2015 ohsu-metagenome
2015 ohsu-metagenome
 
2015 pag-metagenome
2015 pag-metagenome2015 pag-metagenome
2015 pag-metagenome
 

Similar to C++ metaprogramming

The Future of C++
The Future of C++The Future of C++
The Future of C++
Sasha Goldshtein
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
GlobalLogic Ukraine
 
C++0x Variadic Type List
C++0x Variadic Type ListC++0x Variadic Type List
C++0x Variadic Type ListAkira Takahashi
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
Anton Kolotaev
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Templates
TemplatesTemplates
Lecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdfLecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdf
MianSaeedAkbar1
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
Saiganesh124618
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
Seok-joon Yun
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.ppt
Abdullah Yousafzai
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
guestf0562b
 
02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De DadosTiago Romão
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
sivakumarmcs
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
BhushanLilhare
 

Similar to C++ metaprogramming (20)

The Future of C++
The Future of C++The Future of C++
The Future of C++
 
C++ Templates. SFINAE
C++ Templates. SFINAEC++ Templates. SFINAE
C++ Templates. SFINAE
 
C++0x Variadic Type List
C++0x Variadic Type ListC++0x Variadic Type List
C++0x Variadic Type List
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Templates
TemplatesTemplates
Templates
 
Lecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdfLecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdf
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
an introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.pptan introduction to c++ templates-comprehensive guide.ppt
an introduction to c++ templates-comprehensive guide.ppt
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados02 Symbian Os Basics Tipos De Dados
02 Symbian Os Basics Tipos De Dados
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 

Recently uploaded

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
vrstrong314
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

C++ metaprogramming

  • 1. Arindam Mukherjee Pune C++ and Boost Meetup C++TEMPLATE METAPROGRAMMING
  • 2. Template type computations  Templates provide a Turing complete computation subsystem – that runs during compilation.  This capability was not entirely consciously designed.  Erwin Unruh found this somewhat accidentally ~ early 90s.
  • 3. Templates  Compile time entities completely evaluated by the compiler, based on arguments passed. std::vector<int> nums; // std::vector<int> unrelated std::vector<std::string> names; // to std::vector<std::string> template <typenameT> class Foo; // declaration template <typenameT> class Foo { … }; // definition Foo<int> foonum; // Foo<int> is specialization
  • 4. Non-type template parameters  Templates can have non-type parameters: template <typename T, int N> struct array { T data[N]; …. }  Non-type args are compile time constants. array<int, 10> arr; // array of 10 ints  sizeof is evaluated at compile time. int arr[sizeof(int)]; // array of 4* ints
  • 5. Embedded types  Typedefs inside a class / class template. template <typename T> struct add_const { typedef const T type; }; add_const<int>::type ci; // const int
  • 6. Embedded constants  Enums inside a class / class template. template <int M, int N> struct add { enum { value = M + N } } int array[add<10, 20>::value];
  • 7. Branching: specializations  Specialize for specific types. template <typename T> struct Foo { … }; // default impl template <> struct Foo<int> { … }; // int-specific  Applicable to function templates too.
  • 8. Partial specializations  Specialize for type families. template <typename T, typename U> struct Foo { … }; // default impl template <typename T> struct Foo<T, T> { … }; // Foo<char, char> template <typename T> struct Foo<T*, T> { … }; // Foo<int*, int>  NOT applicable to function templates.
  • 9. Recursion by specializations  Compute factorial at compile time: template <int N> struct factorial { enum { value = N*factorial<N-1>::value }; }; template <> struct factorial<0> { // terminating condition enum { value = 1 }; };
  • 10. Applying the techniques  Remove const: template <typename T> struct remove_const { typedef T type; }; template <typename T> // partial struct remove_const<const T> { // speclzn typedef T type; };  Called as: remove_const<const int>::type x; // int
  • 11. Applying the techniques  Querying types: template <typename T, typename U> struct are_same { enum { value = 0 }; }; template <typename T> / partial struct are_same<T, T> // specialization { enum { value = 1 }; };  Called as: are_same<int, int>::value == 1;
  • 12. Applying the techniques  Remove levels of indirection: template <typename T> struct deref { typedef T type; }; template <typename T> // partial struct deref<T*> { // specialization typedef typename deref<T>::type type; }  Called as: deref<int*****>::type x; // x is int
  • 13. Boost Type Traits  A header-only library to query and manipulate types at compile time.  Lots of trait metafunctions. #include <boost/type_traits.hpp> typedef int* intptr; assert(boost::is_ptr<intptr>::value); struct Foo {int a; void *b; float c; }; assert(boost::is_pod<Foo>::value);
  • 14. SFINAE  Compiler tries to resolve function calls to a unique overload, or unique template with appropriate arguments.  Multiple templates may be candidates but a unique one must survive.  All candidates instantiated.  Those that fail instantiation eliminated. Not An Error if a single candidate survives.
  • 15. SFINAE & enable_if  Exploit SFINAE to resolve to apt template.  boost::enable_if #include <boost/utility/enable_if.hpp> boost::enable_if<true, T>::type x; // T boost::enable_if<false, T>::type y; //!def  boost::disable_if (opposite of enable_if).
  • 16. SFINAE & enable_if (contd.)  Serialize arbitrary types: #include <boost/utility/enable_if.hpp> typedef vector<char> buffer_t; template <typename T> buffer_t serialize(const T&);  Need a fast version for POD types and generic version for non-POD types. template <typename T> enable_if<is_pod<T>, vector<char>>::type serialize(const T&) {…} // pod version // Use disable_if for the non-POD version
  • 17. Metafunctions  Metafunction: a class or class template taking only type parameters, with a single embedded typedef.  All the Boost type traits are metafunctions.  Boost TMP Library: library of metafunctions.  Provides means of composing and generating metafunctions from simpler metafunctions.
  • 18. Boost TMP Library  Metafunctions need to be combined: #include <boost/type_traits.hpp> template <typename T> void foo(T obj) { if (boost::is_pointer<T>::value || boost::is_array<T>::value) { … } else { … } }
  • 19. Boost TMP Library (contd.)  How to make another metafunction that OR’s two type traits. #include <boost/mpl/or.hpp> #include <boost/type_traits.hpp> template <typename T> void foo(T obj) { if (boost::mpl::or_< boost::is_pointer<T>::value , boost::is_array<T>::value >::value) { … } else { … } }
  • 20. Boost TMP Library (contd.)  Numbers can be wrapped in types: #include <boost/mpl/integral_c.hpp> #include <boost/mpl/greater.hpp> #include <boost/type_traits.hpp> namespace mpl = boost::mpl; template <typename T, typename U> struct is_larger : mpl::greater< mpl::integral_c<size_t, sizeof T> , mpl::integral_c<size_t, sizeof U> > {};
  • 21. Thank you!  Q & A  Book: Modern C++ Design – Andrei Alexandrescu  Book: Advanced C++ Template Metaprogramming – Davide di Gennaro  Book: C++ Template Metaprogramming – Dave Abrahams, Aleksey Gurtovoy