SlideShare une entreprise Scribd logo
1  sur  77
C++ Templates. SFINAE.
Denys Petrov
September 2019
3
Agenda
1. Template syntax by standards
2. SFINAE
3. Introspection and reflection at compile-time
4. Partial and full specialization
5. Conditional expressions
6. Transformations
7. Conditional statements
8. Tag dispatching
4
Template Syntax by Standards
5
Templates of:
● functions
● classes
Kind of template parameters:
● type
● non-type integral types only
● template
template <typename T>
void function() {}
template <typename T>
class Class {};
template <typename T>
template <int i>
template <template < typename > class T>
Keywords:
● template
● typename
● class
С++03
6
class vs typename
typename
• introduced to replace class
keyword and to avoid confusions
• used in template context only
class
• initially used as template parameter
by Bjarne Stroustrup before official
C++98
• used for class declarations
Both keywords are interchangeable except two cases:
• template <template < typename > class T> // until С++17
• typename T::type;
7
Parameter pack and operator sizeof...
template <typename... T>
void function(T... args)
{
const int num = sizeof...(args);
const int sum = (args + ...);
}
constexpr int x = 42;
constexpr int pow2(int n)
{
return n * n;
}
Keyword constexpr
С++11
New context for keyword using
using AliasType = MyClass;
using AliasType = MyClass <int>;
template<typename T>
using AliasType = MyClass <T>;
int x = 42;
decltype(x) var1; // int
int& function(int);
decltype(function(x)) var2; // int&
Keyword decltype
8
typedef vs using
typedef
assign synonyms to:
• types
• fully specialized templates
typedef int Int;
typedef void (*FuncPtr) (int);
typedef typename std::vector < int >::iterator IteratorInt;
template<typename T> using Vector = std::vector < T >;
template<typename T> using Iterator = typename std::vector < T >::iterator;
using Int = int;
using FuncPtr = void (*) (int);
using IteratorInt = typename std::vector < int >::iterator;
using
assign aliases to:
• types
• fully specialized templates
• partially specialized templates
9
Return auto Rvalue reference declarator
auto function()-> int
{
return 42;
}
template <typename T>
auto function2(T t)-> typename T::value_type
{
typename T::value_type v = 42;
return v;
}
template <typename T>
auto function3(T t)-> decltype(t[0])
{
return t[0];
}
void func_int(int&) { }
void func_int(int&&) { }
template <typename T>
void function(T&& t){
func_int(t);
}
function(i); //t = int&, func_int(int&)
function(42); //t = int&&, func_int(int&)
template <typename T>
void function(T&& t){
func_int(std::forward <T> (t));
}
function(i); //t = int&, func_int(int&)
function(42); //t = int&&, func_int(int&&)
С++11
10
Added templates of variables
//function
template <typename T>
void function() {}
//class
template <typename T>
class Class {};
//variables
template <typename T>
const T PI = static_cast <T> (3.14159265);
template <typename T>
constexpr int value = T::value;
С++14
11
Added operator constexpr if
if constexpr (true)
{
// compiled
}
else
{
// discarded
}
if constexpr (sizeof...(args) == 2)
{
// ...
}
if constexpr (false)
{
//static_assert(false);
static_assert(std::dependent_false<T>::value);
}
С++17
12
Template auto as unknown non-type parameter
//function
template <auto value>
void function() {}
//class
template <auto value>
class Class {};
//variadic class
template <auto... value>
class Class {};
Class <42, 'X', true> //heterogeneous
//function
template <typename T, T value>
void function() {}
//class
template <typename T, T value>
class Class {};
//variadic class
template <typename T, T... value>
class Class {};
Class <int, 42, 43, 44> //homogeneous
C++17 C++14
С++17
13
1. Debug > Project Properties > C/C++ > Language > C++ Language Standard
1. Debug > Project Properties > General > C++ Language Standard
Changing Standard in Visual Studio
1
2
3
4
14
Concepts
template <typename T>
concept MyConcept1 = sizeof(T) == 1;
template <typename T>
concept MyConcept2 = false;
template <class T>
concept MyConcept3 = MyConcept1<T> && ! MyConcept2<T>;
template <MyConcept3 T>
struct S {};
С++20
15
SFINAE
16
SFINAE - SUBSTITUTION FAILURE IS NOT AN ERROR
• Abbreviation introduced by David Vandevoorde
• Based on a template syntax
• Result of the order of a template substitution
• Make possible a reflection
• Constrains the range of applied types
17
Existing Implementations of SFINAE
• <boost/type_traits.hpp> boost
• <type_traits> STL
• <xtr1common> STL
• <Windows Kits10Include10.0.16299.0winrtwrlinternal.h>
• <Windows Kits10Include10.0.16299.0ucrtcorecrt.h>
• <Windows Kits10Include10.0.16299.0winrtwindows.foundation.collections.h>
18
Introspection and Reflection at
Compile-time
19
Introspection and Reflection
Metaprogramming (or Generic Programming) is a technique in which
program have the ability to generate, analyze or transform code using
compile-time computation.
Reflection is the ability of a program to examine, introspect, and modify its
own structure and behavior.
Introspection is the ability of a program to examine the type or properties of
an object at runtime.
Runtime for metaprogramming is a compile-time.
20
Correct Incorrect
template <typename T1, typename T2>
class Class { };
template <typename T>
class Class <T, typename T::NestedType> { };
template <typename T>
class Class : T::NestedType1 { };
template <typename T>
class Class <const T> : T::NestedType2 { };
template <typename T,
typename = typename T::NestedType>
class Class { };
template <typename T>
class Class
{ using type = typename T::NestedType };
template <typename T,
typename = typename T::NestedType>
void function ()
{
}
template <typename T>
void function ()
{
typename T::NestedType var;
}
template <typename T>
auto function (T t) -> decltype(t.foo())
{
return t.foo();
}
template <typename T>
auto function (T t)
{
return t.foo();
}
Use Cases
21
Object Inspection
• Partial and full specialization
- Classes
- Functions
• Conditional expressions
- Boolean types
- Logical operators
- Predicates
• Transformations
- Modifiers
• Conditional statements
- If operator
- Switch operator
• Tag dispatching
22
Partial and Full Specialization
23
Class Template Specialization
Primary class template:
template <typename T1, typename T2>
class Class { };
Full specialization:
template <>
class Class <int, char> { };
Partial specialization:
template <typename T>
class Class <int, const T> { };
Examples:
Class <const char, int&> c1;
Class <int, const int*> c2;
Class <char*, int[10]> c3;
24
template <typename T>
class Class {};
template <typename T>
class Class <const T *> {};
template <typename T>
class Class <const T> {};
Class <int> -> Class <T> -> T = int
Class <const int> -> Class <const T> -> T = int
Class <int * const> -> Class <const T> -> T = int*
Class <const int *> -> Class <const T *> -> T = int
Class <const int * const> -> Class <const T> -> T = const int*
Template Type Deduction
Instantiation Substitution Deduction
25
Type Deduction Table
C - const V - volatile T - type
Parameter
Specialization
26
Example
Class specialization
template<typename T>
class Class {};
template <typename T>
class Class <const T> { };
Class <const volatile int> c1; -> Class <const T> -> T = volatile int
27
Type Deduction Table &
C - const V - volatile T - type
28
Type Deduction Table &&
C - const V - volatile T - type
29
Instantiated type: const volatile int * const volatile
1. Class <const volatile T * const volatile> -> T = int
1. Class <volatile T * const volatile> -> T = const int
1. Class <const T * const volatile> -> T = volatile int
1. Class <T * const volatile> -> T = const volatile int
1. Class <const volatile T> -> T = const volatile int *
1. Class <volatile T> -> T = const volatile int * const
1. Class <const T> -> T = const volatile int * volatile
1. Class <T> -> T = const volatile int * const volatile
* error C2752: more than one partial specialization matches the template argument list
Substitution Preference Order
*
*
30
Partial specialization with lower or equal amount of parameters:
template <typename T>
class Class <int, const T> { }; // ONE type
One More Class Template Specialization
Partial specialization with bigger amount of parameters:
template <template <typename, typename> typename T1, typename T2, typename T3>
class Class <???> { }; // THREE types (one of them is a template type)
template <typename T, size_t value>
class Class <???> { }; // ONE type, ONE variable
template <typename T1, typename T2, typename... T3>
class Class <???> { }; // Variable amount of types (minimum TWO)
Primary class template:
template <typename T1, typename T2>
class Class { }; // TWO types
31
One More Class Template Specialization
Partial specialization with bigger amount of parameters:
template <template <typename, typename> typename T1, typename T2, typename T3>
class Class <T1 <T2, T3>, T2&> { }; // std::vector<int>
template <typename T, size_t value>
class Class <T[value], T> { }; // char[10]
template <typename T1, typename T2, typename... T3>
class Class <T1(*)(T3...), T2> { }; // int(*)(float&, const int)
Partial specialization with lower or equal amount of parameters:
template <typename T>
class Class <int, const T> { };
Primary class template:
template <typename T1, typename T2>
class Class { };
32
Function Template Specialization
Function template:
template <typename T>
void func (T) { };
Full specialization:
template <>
void func <int *> (int *) { };
Example:
int i = 42;
func(i);
func(&i);
“Partial” specialization (Overloading):
template <typename T>
void func (T *) { };
33
Function Template Argument Deduction Table
Parameter
Argument
C - const V - volatile T - type
34
Example
Function declaration
template <typename T>
void func(const T arg) { };
int* ptr = nullptr;
function(ptr); -> func <T*> -> decltype(arg) = int * const
35
Function Template Argument Deduction Table &
C - const V - volatile T - type
36
Function Template Argument Deduction Table &&
C - const V - volatile T - type
37
Conditional Expressions
38
Boolean types
bool value1 = true;
bool value2 = false;
struct True
{
};
struct False
{
};
Traditional Programming Metaprogramming
39
Logical operators. Conjunction.
&&
Traditional Programming
template <typename BOOL1, typename BOOL2>
struct AND
{
using result = False;
};
template <>
struct AND <True, True>
{
using result = True;
};
Metaprogramming
40
Logical operators. Disjunction.
||
Traditional Programming Metaprogramming
template <typename BOOL1, typename BOOL2>
struct OR
{
using result = True;
};
template <>
struct OR <False, False>
{
using result = False;
};
41
Logical operators. Inversion.
!
Traditional Programming
template <typename BOOL>
struct NOT
{
using result = False;
};
template <>
struct NOT <False>
{
using result = True;
};
Metaprogramming
42
Example
typename AND <
typename OR <
True,
False
>::result,
typename NOT <
False
>::result
>::result
OR
NOT
AND
( true || false ) && ( ! false )
Traditional Programming
typename AND < typename OR < True, False >::result, typename NOT < False >::result >::result;
Metaprogramming
43
Predicates. Qualifier Check.
bool IsConst(T);
Traditional Programming Metaprogramming
template <typename T>
struct IsConst
{
using result = False;
};
template <typename T>
struct IsConst <const T>
{
using result = True;
};
44
Predicates. Reference Check.
bool IsReference(T);
Traditional Programming Metaprogramming
template <typename T>
struct IsReference
{
using result = False;
};
template <typename T>
struct IsReference <T&>
{
using result = True;
};
45
Class Template With Default Parameter
template <typename T, typename = void>
struct Class { };
template <typename T>
struct Class <T, void> { };
Class <int>; -> struct Class <T, void>
Class <int, void>; -> struct Class <T, void>
Class <int, char>; -> struct Class
46
Complicated Predicates. Method Check.
template <typename T>
using Wrap = void;
template <typename T, typename = void>
struct HasMethodFooImpl { using result = False; };
template <typename T>
struct HasMethodFooImpl <T, Wrap <decltype(&T::foo)> > { using result = True; };
template <typename T>
constexpr bool HasMethodFoo = HasMethodFooImpl <T>::result;
47
Method Check. Painfull version before C++11
template<typename T>
struct HasMethodFooImpl
{
typedef char One;
typedef struct { One x[2]; } Two;
template <typename T, void(T::*func)() = &T::foo>
static One test();
template <typename T>
static Two test(...);
static const bool value = sizeof(test<T>(0)) == sizeof(One);
};
Example
const bool HasMethodFoo = HasMethodFooImpl <T>::value;
48
Transformations
49
Add Сonstancy
Result AddConst(T);
Traditional Programming Metaprogramming
template <typename T>
struct AddConst
{
using result = const T;
};
50
Remove Сonstancy
Result RemoveConst(T);
Traditional Programming Metaprogramming
template <typename T>
struct RemoveConst
{
using result = T;
};
template <typename T>
struct RemoveConst <const T>
{
using result = T;
};
51
Add Method
Result AddMethodFoo(T);
Traditional Programming Metaprogramming
template <typename T>
struct AddMethodFoo
{
using result = struct : T
{
void foo() {}
};
};
52
Remove Method
Result RemoveMethodFoo(T);
Traditional Programming Metaprogramming
template <typename T>
struct RemoveMethodFoo
{
using result = struct : T
{
void f() = delete;
};
};
53
Conditional Statements
54
If Statement
if (<bool expression>)
{
}
Traditional Programming Metaprogramming
template <typename T>
struct IF
{
};
template <>
struct IF <True>
{
using allow = void;
};
55
If Statement Usage
You can put IF statement to the next places:
● Return type
template <typename T>
typename IF <True>::allow function (T) { }
● Function argument
template <typename T>
void function (T, typename IF <True>::allow* = 0) { }
● Default template argument
template < typename T, typename = typename IF <True>::allow >
void function (T) { }
template < typename T, typename = typename IF <True>::allow >
class Class { };
56
Example
if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) )
{
function(t);
}
Traditional Programming
template < typename T, typename = typename IF < typename AND < typename OR < typename
IsConst <T>::result, typename IsReference < typename RemoveConst <T>::result
>::result >::result, typename NOT < typename IsConst < typename AddConst <T>::result
>::result >::result >::result >::allow >
void function (T)
{
}
Metaprogramming
57
Example
template < typename T, typename = typename IF < typename AND < typename OR < typename
IsConst <T>::result, typename IsReference < typename RemoveConst <T>::result >::result
>::result, typename NOT < typename IsConst < typename AddConst <T>::result >::result
>::result >::result >::allow >
void function (T)
{
}
if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) )
{
function(t);
}
Traditional Programming
Metaprogramming
58
Previous syntax Refined syntax
struct True {};
struct False{};
template <bool b>
struct Bool { static constexpr bool value = b; };
struct True : Bool <true> { };
struct False : Bool <false> { };
template <typename T>
struct IsConst { using result = False; };
template <typename T>
struct IsConst <const T> { using result = True; };
template <typename T>
struct IsConstImpl : False { };
template <typename T>
struct IsConstImpl <const T> : True { };
template <typename T>
constexpr bool IsConst = IsConstImpl <T>::value;
template <typename T>
struct AddConst { using result = const T; };
template <typename T>
using AddConst = const T;
template <typename T>
struct IF { };
template <>
struct IF <True> { using allow = void; };
template<bool b>
struct IFImpl;
template <>
struct IFImpl <true> { using allow = void; };
template <bool b>
using IF = typename IFImpl <b>::allow;
Syntax Sugar
59
Example
if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) )
{
function(t);
}
Traditional Programming
template < typename T, typename =
IF < IsConst <T> || IsReference < RemoveConst <T> > && ! IsConst < AddConst <T> > > >
void function (T)
{
}
Metaprogramming
60
Meta-Map
struct key_1 { };
struct key_2 { };
template <typename KEY> class MapTypes { };
template <> struct MapTypes <key_1>
{ using Value = int; };
template <> struct MapTypes <key_2>
{ using Value = float; };
template <typename T> struct MapTypes <const T>
{ using Value = const int; };
template <typename ARRAY, size_t size>
struct MapTypes <ARRAY[size]>
{ using Value = void*; };
Example:
typename MapTypes <???> ::Value x;
template <int KEY> class MapVars { };
template <> struct MapVars <0>
{ static constexpr auto value = 42; };
template <> struct MapVars <1>
{ static constexpr auto value = 3.14; };
template <> struct MapVars <2>
{ static constexpr auto value = “Hello”; };
template <> struct MapVars <3>
{ static constexpr auto value = nullptr; };
Example:
auto x = MapVars <???> ::value;
61
Switch Statement. Cases.
template <bool Value, int Index, int Size = 0>
struct CASE : Bool <Value>
{
static constexpr int index = Index;
static constexpr int size = Size;
};
template <int Size>
using CASE_DEFAULT = CASE <false, 0, Size>;
template <typename T, int index>
struct MyCases : CASE_DEFAULT <4> {};
template <typename T>
struct MyCases <T, 1> : CASE <IsConst <T>, 1> {};
template <typename T>
struct MyCases <T, 2> : CASE <IsReference <T>, 2> {};
template <typename T>
struct MyCases <T, 3> : CASE <HasMethodFoo <T>, 3> {};
62
Switch Statement
template <template <typename, int> typename Cases, typename T, int size = Cases <T, 0>::size>
struct SWITCHImpl
{
static constexpr int index = size > 0 ?
( Cases <T, size>::value ? Cases <T, size>::index : SWITCHImpl <Cases, T, size - 1>::index ) : 0;
};
template <template<typename, int> typename Cases, typename T>
struct SWITCHImpl <Cases, T, 0>
{
static constexpr int index = 0;
};
template <template<typename, int> typename Cases, typename T>
constexpr int SWITCH = SWITCHImpl <Cases, T>::index;
Start
Go through all of
the cases using argument T
Find first true
condition
return index of the
condition
End
63
Switch Statement Usage
if (IsConst <T>)
{
Class <T, 1> c;
}
else if (IsReference <T>)
{
Class <T, 2> c;
}
else if (HasMethodFoo <T>)
{
Class <T, 3> c;
}
Traditional Programming Metaprogramming
template <typename T, int X>
struct Class { static_assert(false); /*error*/ };
template <typename T>
struct Class <T, 1> { /* implementation #1 */ };
template <typename T>
struct Class <T, 2> { /* implementation #2 */ };
template <typename T>
struct Class <T, 3> { /* implementation #3 */ };
Example
Class <T, SWITCH <MyCases, T>> c;
64
Switch Statement Usage. C++17.
/*
...
a lot preceding stuff...
...
*/
template <typename T>
void function (T)
{
Class <T, SWITCH <MyCases, T>> c;
}
C++14 C++17
template <typename T>
void function (T)
{
if constexpr (IsConst <T>)
{
Class <T, 1> c;
}
else if constexpr (IsReference <T>)
{
Class <T, 2> c;
}
else if constexpr (HasMethodFoo <T>)
{
Class <T, 3> c;
}
else
{
static_assert(false); // error
}
}
65
Switch Statement For Functions
if (IsConst <T>)
{
function1 ();
}
else if (IsReference <T>)
{
function2 ();
}
else if (HasMethodFoo <T>)
{
function3 ();
}
Traditional Programming Metaprogramming
template <int index> struct Tag { };
template <typename T>
void function (Tag <0>)
{ static_assert(template_false <T>); }
template <typename T>
void function (Tag <1>) { /* implementation #1 */ }
template <typename T>
void function (Tag <2>) { /* implementation #2 */ }
template <typename T>
void function (Tag <3>) { /* implementation #3 */ }
Example
function <T> ( Tag <SWITCH <MyCases, T>> () );
66
Static Assert at Compile-time
Compiler generates an error every time while meeting a false condition.
Use variable template to make compiler generate an error only when it
instantiates the template. It allows to avoid an instant error.
Wrong
template <typename T>
struct Class
{
static_assert(false);
};
Correct
template <typename T>
constexpr bool template_false = false;
template <typename T>
struct Class
{
static_assert(template_false <T>);
};
67
Tag Dispatching
68
Dummy Type
// created from GUID {A031ECDEA-A7E5-4D9F-B7F8-77756FC30480}
struct A031ECDEA7E54D9FB7F877756FC30480{ };
using Dummy = A031ECDEA7E54D9FB7F877756FC30480;
template <typename T>
struct FunctionReturnTypeImpl
{
using result = Dummy;
};
template <typename Return, typename... Args>
struct FunctionReturnTypeImpl <Return(*)(Args...)>
{
using result = Return;
};
template <typename T>
using FunctionReturnType = typename FunctionReturnTypeImpl <T>::result;
69
Tag Dispatching in STL Iterators
random access
iterator
bidirectional
iterator
forward iterator
input iterator ++ (single-pass only) !=
++
--
+= -= + - > < >= <=
70
Tag Dispatching in STL Iterators
iterator_base
vector_iterator list_iterator forward_list_iterator deque_iterator string_iterator
input_iterator_tag
forward_iterator_tag
bidirectional_iterator_tag
random_access_iterator_tag
71
Iterator Tags
struct input_iterator_tag { };
struct forward_iterator_tag : input_iterator_tag { };
struct bidirectional_iterator_tag : forward_iterator_tag { };
struct random_access_iterator_tag : bidirectional_iterator_tag { };
template <class _Iter>
constexpr bool _Is_input_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, input_iterator_tag>;
template <class _Iter>
constexpr bool _Is_fwd_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, forward_iterator_tag>;
template <class _Iter>
constexpr bool _Is_bidi_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, bidirectional_iterator_tag>;
template <class _Iter>
constexpr bool _Is_random_iter_v = is_convertible_v <_Iter_cat_t <_Iter>,
random_access_iterator_tag>;
72
std::advance
template <class Iterator, class Diff>
void advance (Iterator & iter, Diff offset)
{
static_assert (_Is_input_iter_v <Iterator>, "next requires input iterator");
if constexpr (_Is_random_iter_v <Iterator>)
{
iter += offset;
}
else
{
if constexpr (is_signed_v <Diff>)
{
if constexpr (_Is_bidi_iter_v <Iterator>)
{
for (; offset < 0; ++offset, --iter)
}
else
{
static_assert (offset >= 0, "negative advance of non-bidirectional iterator");
}
}
for (; 0 < offset; --offset, ++iter);
}
}
73
Use SFINAE when
● Diagnose and warn about wrong code usage
● Create self-sufficient common components
● Create ecosystem of objects, common algorithms, libraries
● It is hidden from code users
● It helps to use the code easier
● There is someone who can review and maintain your code
74
Acknowledgement
● youtube.com (CppCon 2017: Arthur O'Dwyer “A Soupçon of SFINAE”)
● youtube.com (Compile-time type introspection using SFINAE)
● youtube.com (C++Now 2018: Agustín Bergé “SFINAE: Substitution Failure Is Not An Error”)
● youtube.com (Compile-time type introspection using SFINAE)
● cppreference.com (Templates)
● habr.com (Упрощение кода с помощью if constexpr в C++17)
● habr.com (Жизнь во время компиляции)
● wikipedia.org (SFINAE)
● isocpp.org (Templates)
● Visual Studio STL sources
Questions?
September 2019
Thank you
Denys Petrov
Senior Software Engineer
C++ Templates. SFINAE

Contenu connexe

Tendances (20)

Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
B.sc CSIT 2nd semester C++ Unit3
B.sc CSIT  2nd semester C++ Unit3B.sc CSIT  2nd semester C++ Unit3
B.sc CSIT 2nd semester C++ Unit3
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
This pointer
This pointerThis pointer
This pointer
 
Class template
Class templateClass template
Class template
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Search methods
Search methodsSearch methods
Search methods
 
Friend functions
Friend functions Friend functions
Friend functions
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
class and objects
class and objectsclass and objects
class and objects
 
Type conversion
Type  conversionType  conversion
Type conversion
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 

Similaire à C++ Templates. SFINAE

Similaire à C++ Templates. SFINAE (20)

C++ metaprogramming
C++ metaprogrammingC++ metaprogramming
C++ metaprogramming
 
Templates
TemplatesTemplates
Templates
 
C++ metaprogramming
C++ metaprogrammingC++ metaprogramming
C++ metaprogramming
 
C++0x Variadic Type List
C++0x Variadic Type ListC++0x Variadic Type List
C++0x Variadic Type List
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates2 BytesC++ course_2014_c13_ templates
2 BytesC++ course_2014_c13_ templates
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
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
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Lecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdfLecture 2.6 Function Templates.pdf
Lecture 2.6 Function Templates.pdf
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates2
Templates2Templates2
Templates2
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Templates in c++
Templates in c++Templates in c++
Templates in 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
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
Savitch ch 17
Savitch ch 17Savitch ch 17
Savitch ch 17
 
Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile Time
 
Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++
 

Plus de GlobalLogic Ukraine

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxGlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxGlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxGlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationGlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"GlobalLogic Ukraine
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Ukraine
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"GlobalLogic Ukraine
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Ukraine
 

Plus de GlobalLogic Ukraine (20)

GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptxШтучний інтелект як допомога в навчанні, а не замінник.pptx
Штучний інтелект як допомога в навчанні, а не замінник.pptx
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptxЗадачі AI-розробника як застосовується штучний інтелект.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptxЩо треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"JavaScript Community Webinar #14 "Why Is Git Rebase?"
JavaScript Community Webinar #14 "Why Is Git Rebase?"
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
 
Страх і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic EducationСтрах і сила помилок - IT Inside від GlobalLogic Education
Страх і сила помилок - IT Inside від GlobalLogic Education
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
 
GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"GlobalLogic Webinar "Introduction to Embedded QA"
GlobalLogic Webinar "Introduction to Embedded QA"
 
C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"C++ Webinar "Why Should You Learn C++ in 2021-22?"
C++ Webinar "Why Should You Learn C++ in 2021-22?"
 
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
GlobalLogic Test Automation Live Testing Session “Android Behind UI — Testing...
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

C++ Templates. SFINAE

  • 1.
  • 2. C++ Templates. SFINAE. Denys Petrov September 2019
  • 3. 3 Agenda 1. Template syntax by standards 2. SFINAE 3. Introspection and reflection at compile-time 4. Partial and full specialization 5. Conditional expressions 6. Transformations 7. Conditional statements 8. Tag dispatching
  • 5. 5 Templates of: ● functions ● classes Kind of template parameters: ● type ● non-type integral types only ● template template <typename T> void function() {} template <typename T> class Class {}; template <typename T> template <int i> template <template < typename > class T> Keywords: ● template ● typename ● class С++03
  • 6. 6 class vs typename typename • introduced to replace class keyword and to avoid confusions • used in template context only class • initially used as template parameter by Bjarne Stroustrup before official C++98 • used for class declarations Both keywords are interchangeable except two cases: • template <template < typename > class T> // until С++17 • typename T::type;
  • 7. 7 Parameter pack and operator sizeof... template <typename... T> void function(T... args) { const int num = sizeof...(args); const int sum = (args + ...); } constexpr int x = 42; constexpr int pow2(int n) { return n * n; } Keyword constexpr С++11 New context for keyword using using AliasType = MyClass; using AliasType = MyClass <int>; template<typename T> using AliasType = MyClass <T>; int x = 42; decltype(x) var1; // int int& function(int); decltype(function(x)) var2; // int& Keyword decltype
  • 8. 8 typedef vs using typedef assign synonyms to: • types • fully specialized templates typedef int Int; typedef void (*FuncPtr) (int); typedef typename std::vector < int >::iterator IteratorInt; template<typename T> using Vector = std::vector < T >; template<typename T> using Iterator = typename std::vector < T >::iterator; using Int = int; using FuncPtr = void (*) (int); using IteratorInt = typename std::vector < int >::iterator; using assign aliases to: • types • fully specialized templates • partially specialized templates
  • 9. 9 Return auto Rvalue reference declarator auto function()-> int { return 42; } template <typename T> auto function2(T t)-> typename T::value_type { typename T::value_type v = 42; return v; } template <typename T> auto function3(T t)-> decltype(t[0]) { return t[0]; } void func_int(int&) { } void func_int(int&&) { } template <typename T> void function(T&& t){ func_int(t); } function(i); //t = int&, func_int(int&) function(42); //t = int&&, func_int(int&) template <typename T> void function(T&& t){ func_int(std::forward <T> (t)); } function(i); //t = int&, func_int(int&) function(42); //t = int&&, func_int(int&&) С++11
  • 10. 10 Added templates of variables //function template <typename T> void function() {} //class template <typename T> class Class {}; //variables template <typename T> const T PI = static_cast <T> (3.14159265); template <typename T> constexpr int value = T::value; С++14
  • 11. 11 Added operator constexpr if if constexpr (true) { // compiled } else { // discarded } if constexpr (sizeof...(args) == 2) { // ... } if constexpr (false) { //static_assert(false); static_assert(std::dependent_false<T>::value); } С++17
  • 12. 12 Template auto as unknown non-type parameter //function template <auto value> void function() {} //class template <auto value> class Class {}; //variadic class template <auto... value> class Class {}; Class <42, 'X', true> //heterogeneous //function template <typename T, T value> void function() {} //class template <typename T, T value> class Class {}; //variadic class template <typename T, T... value> class Class {}; Class <int, 42, 43, 44> //homogeneous C++17 C++14 С++17
  • 13. 13 1. Debug > Project Properties > C/C++ > Language > C++ Language Standard 1. Debug > Project Properties > General > C++ Language Standard Changing Standard in Visual Studio 1 2 3 4
  • 14. 14 Concepts template <typename T> concept MyConcept1 = sizeof(T) == 1; template <typename T> concept MyConcept2 = false; template <class T> concept MyConcept3 = MyConcept1<T> && ! MyConcept2<T>; template <MyConcept3 T> struct S {}; С++20
  • 16. 16 SFINAE - SUBSTITUTION FAILURE IS NOT AN ERROR • Abbreviation introduced by David Vandevoorde • Based on a template syntax • Result of the order of a template substitution • Make possible a reflection • Constrains the range of applied types
  • 17. 17 Existing Implementations of SFINAE • <boost/type_traits.hpp> boost • <type_traits> STL • <xtr1common> STL • <Windows Kits10Include10.0.16299.0winrtwrlinternal.h> • <Windows Kits10Include10.0.16299.0ucrtcorecrt.h> • <Windows Kits10Include10.0.16299.0winrtwindows.foundation.collections.h>
  • 19. 19 Introspection and Reflection Metaprogramming (or Generic Programming) is a technique in which program have the ability to generate, analyze or transform code using compile-time computation. Reflection is the ability of a program to examine, introspect, and modify its own structure and behavior. Introspection is the ability of a program to examine the type or properties of an object at runtime. Runtime for metaprogramming is a compile-time.
  • 20. 20 Correct Incorrect template <typename T1, typename T2> class Class { }; template <typename T> class Class <T, typename T::NestedType> { }; template <typename T> class Class : T::NestedType1 { }; template <typename T> class Class <const T> : T::NestedType2 { }; template <typename T, typename = typename T::NestedType> class Class { }; template <typename T> class Class { using type = typename T::NestedType }; template <typename T, typename = typename T::NestedType> void function () { } template <typename T> void function () { typename T::NestedType var; } template <typename T> auto function (T t) -> decltype(t.foo()) { return t.foo(); } template <typename T> auto function (T t) { return t.foo(); } Use Cases
  • 21. 21 Object Inspection • Partial and full specialization - Classes - Functions • Conditional expressions - Boolean types - Logical operators - Predicates • Transformations - Modifiers • Conditional statements - If operator - Switch operator • Tag dispatching
  • 22. 22 Partial and Full Specialization
  • 23. 23 Class Template Specialization Primary class template: template <typename T1, typename T2> class Class { }; Full specialization: template <> class Class <int, char> { }; Partial specialization: template <typename T> class Class <int, const T> { }; Examples: Class <const char, int&> c1; Class <int, const int*> c2; Class <char*, int[10]> c3;
  • 24. 24 template <typename T> class Class {}; template <typename T> class Class <const T *> {}; template <typename T> class Class <const T> {}; Class <int> -> Class <T> -> T = int Class <const int> -> Class <const T> -> T = int Class <int * const> -> Class <const T> -> T = int* Class <const int *> -> Class <const T *> -> T = int Class <const int * const> -> Class <const T> -> T = const int* Template Type Deduction Instantiation Substitution Deduction
  • 25. 25 Type Deduction Table C - const V - volatile T - type Parameter Specialization
  • 26. 26 Example Class specialization template<typename T> class Class {}; template <typename T> class Class <const T> { }; Class <const volatile int> c1; -> Class <const T> -> T = volatile int
  • 27. 27 Type Deduction Table & C - const V - volatile T - type
  • 28. 28 Type Deduction Table && C - const V - volatile T - type
  • 29. 29 Instantiated type: const volatile int * const volatile 1. Class <const volatile T * const volatile> -> T = int 1. Class <volatile T * const volatile> -> T = const int 1. Class <const T * const volatile> -> T = volatile int 1. Class <T * const volatile> -> T = const volatile int 1. Class <const volatile T> -> T = const volatile int * 1. Class <volatile T> -> T = const volatile int * const 1. Class <const T> -> T = const volatile int * volatile 1. Class <T> -> T = const volatile int * const volatile * error C2752: more than one partial specialization matches the template argument list Substitution Preference Order * *
  • 30. 30 Partial specialization with lower or equal amount of parameters: template <typename T> class Class <int, const T> { }; // ONE type One More Class Template Specialization Partial specialization with bigger amount of parameters: template <template <typename, typename> typename T1, typename T2, typename T3> class Class <???> { }; // THREE types (one of them is a template type) template <typename T, size_t value> class Class <???> { }; // ONE type, ONE variable template <typename T1, typename T2, typename... T3> class Class <???> { }; // Variable amount of types (minimum TWO) Primary class template: template <typename T1, typename T2> class Class { }; // TWO types
  • 31. 31 One More Class Template Specialization Partial specialization with bigger amount of parameters: template <template <typename, typename> typename T1, typename T2, typename T3> class Class <T1 <T2, T3>, T2&> { }; // std::vector<int> template <typename T, size_t value> class Class <T[value], T> { }; // char[10] template <typename T1, typename T2, typename... T3> class Class <T1(*)(T3...), T2> { }; // int(*)(float&, const int) Partial specialization with lower or equal amount of parameters: template <typename T> class Class <int, const T> { }; Primary class template: template <typename T1, typename T2> class Class { };
  • 32. 32 Function Template Specialization Function template: template <typename T> void func (T) { }; Full specialization: template <> void func <int *> (int *) { }; Example: int i = 42; func(i); func(&i); “Partial” specialization (Overloading): template <typename T> void func (T *) { };
  • 33. 33 Function Template Argument Deduction Table Parameter Argument C - const V - volatile T - type
  • 34. 34 Example Function declaration template <typename T> void func(const T arg) { }; int* ptr = nullptr; function(ptr); -> func <T*> -> decltype(arg) = int * const
  • 35. 35 Function Template Argument Deduction Table & C - const V - volatile T - type
  • 36. 36 Function Template Argument Deduction Table && C - const V - volatile T - type
  • 38. 38 Boolean types bool value1 = true; bool value2 = false; struct True { }; struct False { }; Traditional Programming Metaprogramming
  • 39. 39 Logical operators. Conjunction. && Traditional Programming template <typename BOOL1, typename BOOL2> struct AND { using result = False; }; template <> struct AND <True, True> { using result = True; }; Metaprogramming
  • 40. 40 Logical operators. Disjunction. || Traditional Programming Metaprogramming template <typename BOOL1, typename BOOL2> struct OR { using result = True; }; template <> struct OR <False, False> { using result = False; };
  • 41. 41 Logical operators. Inversion. ! Traditional Programming template <typename BOOL> struct NOT { using result = False; }; template <> struct NOT <False> { using result = True; }; Metaprogramming
  • 42. 42 Example typename AND < typename OR < True, False >::result, typename NOT < False >::result >::result OR NOT AND ( true || false ) && ( ! false ) Traditional Programming typename AND < typename OR < True, False >::result, typename NOT < False >::result >::result; Metaprogramming
  • 43. 43 Predicates. Qualifier Check. bool IsConst(T); Traditional Programming Metaprogramming template <typename T> struct IsConst { using result = False; }; template <typename T> struct IsConst <const T> { using result = True; };
  • 44. 44 Predicates. Reference Check. bool IsReference(T); Traditional Programming Metaprogramming template <typename T> struct IsReference { using result = False; }; template <typename T> struct IsReference <T&> { using result = True; };
  • 45. 45 Class Template With Default Parameter template <typename T, typename = void> struct Class { }; template <typename T> struct Class <T, void> { }; Class <int>; -> struct Class <T, void> Class <int, void>; -> struct Class <T, void> Class <int, char>; -> struct Class
  • 46. 46 Complicated Predicates. Method Check. template <typename T> using Wrap = void; template <typename T, typename = void> struct HasMethodFooImpl { using result = False; }; template <typename T> struct HasMethodFooImpl <T, Wrap <decltype(&T::foo)> > { using result = True; }; template <typename T> constexpr bool HasMethodFoo = HasMethodFooImpl <T>::result;
  • 47. 47 Method Check. Painfull version before C++11 template<typename T> struct HasMethodFooImpl { typedef char One; typedef struct { One x[2]; } Two; template <typename T, void(T::*func)() = &T::foo> static One test(); template <typename T> static Two test(...); static const bool value = sizeof(test<T>(0)) == sizeof(One); }; Example const bool HasMethodFoo = HasMethodFooImpl <T>::value;
  • 49. 49 Add Сonstancy Result AddConst(T); Traditional Programming Metaprogramming template <typename T> struct AddConst { using result = const T; };
  • 50. 50 Remove Сonstancy Result RemoveConst(T); Traditional Programming Metaprogramming template <typename T> struct RemoveConst { using result = T; }; template <typename T> struct RemoveConst <const T> { using result = T; };
  • 51. 51 Add Method Result AddMethodFoo(T); Traditional Programming Metaprogramming template <typename T> struct AddMethodFoo { using result = struct : T { void foo() {} }; };
  • 52. 52 Remove Method Result RemoveMethodFoo(T); Traditional Programming Metaprogramming template <typename T> struct RemoveMethodFoo { using result = struct : T { void f() = delete; }; };
  • 54. 54 If Statement if (<bool expression>) { } Traditional Programming Metaprogramming template <typename T> struct IF { }; template <> struct IF <True> { using allow = void; };
  • 55. 55 If Statement Usage You can put IF statement to the next places: ● Return type template <typename T> typename IF <True>::allow function (T) { } ● Function argument template <typename T> void function (T, typename IF <True>::allow* = 0) { } ● Default template argument template < typename T, typename = typename IF <True>::allow > void function (T) { } template < typename T, typename = typename IF <True>::allow > class Class { };
  • 56. 56 Example if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) ) { function(t); } Traditional Programming template < typename T, typename = typename IF < typename AND < typename OR < typename IsConst <T>::result, typename IsReference < typename RemoveConst <T>::result >::result >::result, typename NOT < typename IsConst < typename AddConst <T>::result >::result >::result >::result >::allow > void function (T) { } Metaprogramming
  • 57. 57 Example template < typename T, typename = typename IF < typename AND < typename OR < typename IsConst <T>::result, typename IsReference < typename RemoveConst <T>::result >::result >::result, typename NOT < typename IsConst < typename AddConst <T>::result >::result >::result >::result >::allow > void function (T) { } if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) ) { function(t); } Traditional Programming Metaprogramming
  • 58. 58 Previous syntax Refined syntax struct True {}; struct False{}; template <bool b> struct Bool { static constexpr bool value = b; }; struct True : Bool <true> { }; struct False : Bool <false> { }; template <typename T> struct IsConst { using result = False; }; template <typename T> struct IsConst <const T> { using result = True; }; template <typename T> struct IsConstImpl : False { }; template <typename T> struct IsConstImpl <const T> : True { }; template <typename T> constexpr bool IsConst = IsConstImpl <T>::value; template <typename T> struct AddConst { using result = const T; }; template <typename T> using AddConst = const T; template <typename T> struct IF { }; template <> struct IF <True> { using allow = void; }; template<bool b> struct IFImpl; template <> struct IFImpl <true> { using allow = void; }; template <bool b> using IF = typename IFImpl <b>::allow; Syntax Sugar
  • 59. 59 Example if( IsConst(T) || IsReference( RemoveConst(T) ) ) && ( ! IsConst( AddConst(T) ) ) { function(t); } Traditional Programming template < typename T, typename = IF < IsConst <T> || IsReference < RemoveConst <T> > && ! IsConst < AddConst <T> > > > void function (T) { } Metaprogramming
  • 60. 60 Meta-Map struct key_1 { }; struct key_2 { }; template <typename KEY> class MapTypes { }; template <> struct MapTypes <key_1> { using Value = int; }; template <> struct MapTypes <key_2> { using Value = float; }; template <typename T> struct MapTypes <const T> { using Value = const int; }; template <typename ARRAY, size_t size> struct MapTypes <ARRAY[size]> { using Value = void*; }; Example: typename MapTypes <???> ::Value x; template <int KEY> class MapVars { }; template <> struct MapVars <0> { static constexpr auto value = 42; }; template <> struct MapVars <1> { static constexpr auto value = 3.14; }; template <> struct MapVars <2> { static constexpr auto value = “Hello”; }; template <> struct MapVars <3> { static constexpr auto value = nullptr; }; Example: auto x = MapVars <???> ::value;
  • 61. 61 Switch Statement. Cases. template <bool Value, int Index, int Size = 0> struct CASE : Bool <Value> { static constexpr int index = Index; static constexpr int size = Size; }; template <int Size> using CASE_DEFAULT = CASE <false, 0, Size>; template <typename T, int index> struct MyCases : CASE_DEFAULT <4> {}; template <typename T> struct MyCases <T, 1> : CASE <IsConst <T>, 1> {}; template <typename T> struct MyCases <T, 2> : CASE <IsReference <T>, 2> {}; template <typename T> struct MyCases <T, 3> : CASE <HasMethodFoo <T>, 3> {};
  • 62. 62 Switch Statement template <template <typename, int> typename Cases, typename T, int size = Cases <T, 0>::size> struct SWITCHImpl { static constexpr int index = size > 0 ? ( Cases <T, size>::value ? Cases <T, size>::index : SWITCHImpl <Cases, T, size - 1>::index ) : 0; }; template <template<typename, int> typename Cases, typename T> struct SWITCHImpl <Cases, T, 0> { static constexpr int index = 0; }; template <template<typename, int> typename Cases, typename T> constexpr int SWITCH = SWITCHImpl <Cases, T>::index; Start Go through all of the cases using argument T Find first true condition return index of the condition End
  • 63. 63 Switch Statement Usage if (IsConst <T>) { Class <T, 1> c; } else if (IsReference <T>) { Class <T, 2> c; } else if (HasMethodFoo <T>) { Class <T, 3> c; } Traditional Programming Metaprogramming template <typename T, int X> struct Class { static_assert(false); /*error*/ }; template <typename T> struct Class <T, 1> { /* implementation #1 */ }; template <typename T> struct Class <T, 2> { /* implementation #2 */ }; template <typename T> struct Class <T, 3> { /* implementation #3 */ }; Example Class <T, SWITCH <MyCases, T>> c;
  • 64. 64 Switch Statement Usage. C++17. /* ... a lot preceding stuff... ... */ template <typename T> void function (T) { Class <T, SWITCH <MyCases, T>> c; } C++14 C++17 template <typename T> void function (T) { if constexpr (IsConst <T>) { Class <T, 1> c; } else if constexpr (IsReference <T>) { Class <T, 2> c; } else if constexpr (HasMethodFoo <T>) { Class <T, 3> c; } else { static_assert(false); // error } }
  • 65. 65 Switch Statement For Functions if (IsConst <T>) { function1 (); } else if (IsReference <T>) { function2 (); } else if (HasMethodFoo <T>) { function3 (); } Traditional Programming Metaprogramming template <int index> struct Tag { }; template <typename T> void function (Tag <0>) { static_assert(template_false <T>); } template <typename T> void function (Tag <1>) { /* implementation #1 */ } template <typename T> void function (Tag <2>) { /* implementation #2 */ } template <typename T> void function (Tag <3>) { /* implementation #3 */ } Example function <T> ( Tag <SWITCH <MyCases, T>> () );
  • 66. 66 Static Assert at Compile-time Compiler generates an error every time while meeting a false condition. Use variable template to make compiler generate an error only when it instantiates the template. It allows to avoid an instant error. Wrong template <typename T> struct Class { static_assert(false); }; Correct template <typename T> constexpr bool template_false = false; template <typename T> struct Class { static_assert(template_false <T>); };
  • 68. 68 Dummy Type // created from GUID {A031ECDEA-A7E5-4D9F-B7F8-77756FC30480} struct A031ECDEA7E54D9FB7F877756FC30480{ }; using Dummy = A031ECDEA7E54D9FB7F877756FC30480; template <typename T> struct FunctionReturnTypeImpl { using result = Dummy; }; template <typename Return, typename... Args> struct FunctionReturnTypeImpl <Return(*)(Args...)> { using result = Return; }; template <typename T> using FunctionReturnType = typename FunctionReturnTypeImpl <T>::result;
  • 69. 69 Tag Dispatching in STL Iterators random access iterator bidirectional iterator forward iterator input iterator ++ (single-pass only) != ++ -- += -= + - > < >= <=
  • 70. 70 Tag Dispatching in STL Iterators iterator_base vector_iterator list_iterator forward_list_iterator deque_iterator string_iterator input_iterator_tag forward_iterator_tag bidirectional_iterator_tag random_access_iterator_tag
  • 71. 71 Iterator Tags struct input_iterator_tag { }; struct forward_iterator_tag : input_iterator_tag { }; struct bidirectional_iterator_tag : forward_iterator_tag { }; struct random_access_iterator_tag : bidirectional_iterator_tag { }; template <class _Iter> constexpr bool _Is_input_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, input_iterator_tag>; template <class _Iter> constexpr bool _Is_fwd_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, forward_iterator_tag>; template <class _Iter> constexpr bool _Is_bidi_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, bidirectional_iterator_tag>; template <class _Iter> constexpr bool _Is_random_iter_v = is_convertible_v <_Iter_cat_t <_Iter>, random_access_iterator_tag>;
  • 72. 72 std::advance template <class Iterator, class Diff> void advance (Iterator & iter, Diff offset) { static_assert (_Is_input_iter_v <Iterator>, "next requires input iterator"); if constexpr (_Is_random_iter_v <Iterator>) { iter += offset; } else { if constexpr (is_signed_v <Diff>) { if constexpr (_Is_bidi_iter_v <Iterator>) { for (; offset < 0; ++offset, --iter) } else { static_assert (offset >= 0, "negative advance of non-bidirectional iterator"); } } for (; 0 < offset; --offset, ++iter); } }
  • 73. 73 Use SFINAE when ● Diagnose and warn about wrong code usage ● Create self-sufficient common components ● Create ecosystem of objects, common algorithms, libraries ● It is hidden from code users ● It helps to use the code easier ● There is someone who can review and maintain your code
  • 74. 74 Acknowledgement ● youtube.com (CppCon 2017: Arthur O'Dwyer “A Soupçon of SFINAE”) ● youtube.com (Compile-time type introspection using SFINAE) ● youtube.com (C++Now 2018: Agustín Bergé “SFINAE: Substitution Failure Is Not An Error”) ● youtube.com (Compile-time type introspection using SFINAE) ● cppreference.com (Templates) ● habr.com (Упрощение кода с помощью if constexpr в C++17) ● habr.com (Жизнь во время компиляции) ● wikipedia.org (SFINAE) ● isocpp.org (Templates) ● Visual Studio STL sources
  • 76. September 2019 Thank you Denys Petrov Senior Software Engineer