fbpx ...

Templates – Advanced techniques

Basic usage of C++ templates may not be enough to utilize opportunities, which were introduced in the latest C++ standards. From C++11 we can use templates with any number of parameters and use a simplified mechanism for SFINAE, which is claimed to be a real C++ wizardry.

We will analyse such code

  #include <type_traits>

struct A {
    virtual ~A() {}
};

// #1 return type
template<class T>
auto construct(T* t) ->
typename std::enable_if_t<std::has_virtual_destructor_v<T>, T>* 
{
    return new T{};
}

template<class T>
T* construct2(
    T* t, 
    typename std::enable_if_t<std::has_virtual_destructor_v<T>>* = nullptr
){
    return new T{};
}

template<class T,
         typename std::enable_if_t<std::has_virtual_destructor_v<T>>* = nullptr>
T* construct3(T* t)
{ return new T{}; }

int main() {
    int* ptr = new int(4);
    A* aptr = new A{};
    auto result = construct3(aptr);
    return 0;
}  
  #include <type_traits>
#include <iostream>

struct Point1D {
    int x;
};
struct Point2D {
    int x, y;
};
struct Point3D {
    int x, y, z;
};
int getY(const Point1D & p) {
    std::cout << "Point1D\n";
    return 0;
}
template <typename T>
int getY(const T & p)
{
    std::cout << "Template\n";
    return p.y;
}

int main() {
    Point1D a { 1 };
    Point2D b { 1, 2 };
    Point3D c { 1, 2, 3 };

    getY(a);
    getY(b);
    getY(c);
    return 0;
}  

Your abilities after Templates – Advanced techniques training

Agenda

Activities

Duration

Form

Order Templates – Advanced techniques training

Related trainings

Templates: basics

Necessary knowledge to understand techniques from this session

Move semantics

Forwarding references and perfect forwarding are used in template functions, especially in variadic ones
ninjaletter

Już uciekasz?

Zanim to zrobisz, zapisz się na Ninjaletter, aby wiedzieć, co piszczy w C++. 

Informujemy, iż w celu realizacji usług dostępnych w naszym serwisie, optymalizacji jej treści, dostosowania strony do Państwa indywidualnych potrzeb oraz wyświetlania, personalizacji i mierzenia skuteczności reklam w ramach zewnętrznych sieci reklamowych korzystamy z informacji zapisanych za pomocą plików cookies na urządzeniach końcowych użytkowników. Pliki cookies można kontrolować za pomocą ustawień swojej przeglądarki internetowej. Dalsze korzystanie z naszego serwisu, bez zmiany ustawień przeglądarki internetowej oznacza, iż użytkownik akceptuje stosowanie plików cookies. Więcej informacji zawartych jest w polityce prywatności serwisu.