7 Advanced C++ Concepts You Should Know
Tags: cpp, programming, tutorial, computerscience
Published: 2019-12-09 00:11:10

<!-- wp:paragraph -->
<p>So I have started updating myself with Modern C++ a while ago &amp; since my post <a rel="noreferrer noopener" aria-label="21 new features of Modern C++ to use in your project (opens in a new tab)" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#1014e5" class="color">21 new features of Modern C++ to use in your project</span></a> &amp; <a rel="noreferrer noopener" aria-label="All about lambda function in C++ (opens in a new tab)" href="http://www.vishalchovatiya.com/learn-lambda-function-in-cpp-with-example/" target="_blank"><span style="color:#1b08eb" class="color">All about lambda function in C++</span></a> was popular I decided to write about advanced C++ concepts &amp; idioms which I have learned from this <a rel="noreferrer noopener" aria-label="wikibook (opens in a new tab)" href="https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms" target="_blank"><span style="color:#0d2ae7" class="color">wikibook</span></a> &amp; <a rel="noreferrer noopener" aria-label="course (opens in a new tab)" href="https://www.udemy.com/course/cpp-in-detail-common-idioms/" target="_blank"><span style="color:#070beb" class="color">course</span></a>.</p>
<!-- /wp:paragraph -->

> /!\\\: This article has been originally published on my blog. If you are interested in receiving my latest articles, [please sign up to my newsletter](http://eepurl.com/gDNybv).


<!-- wp:paragraph -->
<p>There are many other advanced C++ concepts &amp; idioms as well but I would consider these 7 as "should-know". To explain them, I have taken a more pragmatic approach than sophistication. And weighed more on readability, simplicity over other fancy features, syntax sugars and complexity. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong><em>Note:</em></strong> There are also drawbacks of using some of these techniques which I have not discussed here or maybe I am not qualified enough. </p>
<!-- /wp:paragraph -->


<!-- wp:heading {"level":3} -->
<h3 id="RAII">1. RAII</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong> To guarantee the release of resource(s) at the end of a scope.<br><strong><em>Implementation:</em></strong> Wrap resource into a class; resource acquired in the constructor immediately after its allocation; and automatically released in the destructor; resource used via an interface of the class;<br><strong><em>Also known as: </em></strong>Execute-around object, Resource release is finalization, Scope-bound resource management</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Problem</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>R</strong>esource <strong>A</strong>cquisition <strong>I</strong>s <strong>I</strong>nitialization idiom is the most powerful &amp; vastly used idiom although the name is really terrible as the idiom is rather about resource release than acquisition. </li><li>RAII guarantee the release of resource at the end of a scope/destruction. It thus ensures no resource leaks and provides basic <a rel="noreferrer noopener" aria-label="exception safety guarantee (opens in a new tab)" href="http://www.vishalchovatiya.com/7-best-practices-for-exception-handling-in-cpp-with-example/" target="_blank"><span style="color:#0a06e9" class="color">exception safety guarantee</span></a>.</li></ul>
<!-- /wp:list -->

```c++
struct resource
{
    resource(int x, int y) { cout << "resource acquired\n"; }
    ~resource() { cout << "resource destroyed\n"; }
};

void func()
{
    resource *ptr = new resource(1, 2);
    int x;
    std::cout << "Enter an integer: ";
    std::cin >> x;
    if (x == 0)
        throw 0; // the function returns early, and ptr won't be deleted!
    if (x < 0)
        return; // the function returns early, and ptr won't be deleted!
    // do stuff with ptr here
    delete ptr;
}
```

<!-- wp:list -->
<ul><li>In the above code, the early&nbsp;<code>return</code>&nbsp;or&nbsp;<code>throw</code>&nbsp;statement, causing the function to terminate without&nbsp;<code>ptr</code>&nbsp;being deleted.</li><li>Consequently, the memory allocated for variable&nbsp;<code>ptr</code>&nbsp;is now leaked (and leaked again every time this function is called and returns early). </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

```c++
template<class T>
class smart_ptr
{
    T* m_ptr;
public:
    template<typename... Args>
    smart_ptr(Args&&... args) : m_ptr(new T(std::forward<Args>(args)...)){}
    ~smart_ptr() { delete m_ptr; }
    
    smart_ptr(const smart_ptr& rhs) = delete;
    smart_ptr& operator=(const smart_ptr& rhs) = delete;
    
    smart_ptr(smart_ptr&& rhs) : m_ptr(exchange(rhs.m_ptr, nullptr)){}
    smart_ptr& operator=(smart_ptr&& rhs){        
        if (&rhs == this) return *this;
        delete m_ptr;
        m_ptr = exchange(rhs.m_ptr,nullptr);
        return *this;
    }
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
};

void func()
{
    auto ptr = smart_ptr<resource>(1, 2); // now ptr guarantee the release of resource
    // ...
}
```

<!-- wp:list -->
<ul><li>Note that no matter what happens after <code>ptr</code> declaration, <code>ptr</code>&nbsp;will be destroyed when the function terminates (regardless of how it terminates). </li><li>As the&nbsp;<code>ptr</code> is a local <a rel="noreferrer noopener" aria-label="object (opens in a new tab)" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank"><span style="color:#0e1de6" class="color">object</span></a>, the destructor will be called while the <a rel="noreferrer noopener" aria-label="function stack frame (opens in a new tab)" href="http://www.vishalchovatiya.com/how-c-program-convert-into-assembly/" target="_blank"><span style="color:#0715d4" class="color">function stack frame</span></a> rewinds. Hence, we are assured that the&nbsp;<code style="font-size: 16px;">resource</code>&nbsp;will be properly cleaned up. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Using RAII, resources like <code>new</code>/<code>delete</code>, <code>malloc</code>/<code>free</code>, acquire/release,  mutex lock/unlock, file open/close, count <code>++</code>/<code>--</code>,  database connect/disconnect or anything else that exists in limited supply can easily be managed.  </li><li>Examples from C++ Standard Library include <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/" target="_blank"><span style="color:#2116f2" class="color">std::unique_ptr</span></a></code>, <code>std::ofstream</code>, <code>std::lock_guard</code>, etc.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="Return-Type-Resolver">2. Return Type Resolver</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong>  To deduce the type of the object being initialized or assigned to. <br><strong><em>Implementation: </em></strong>Uses templatized conversion operator. <br><strong><em>Also known as: </em></strong> Return type overloading</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Issue</h4>
<!-- /wp:heading -->

```c++
int from_string(const char *str) { return std::stoi(str); }
float from_string(const char *str) { return std::stof(str); } // error
```

<!-- wp:list -->
<ul><li>A function cannot be overloaded only by its return type.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

```c++
class from_string
{
    const string m_str;
public:
    from_string(const char *str) : m_str(str) {}
    template <typename type>
    operator type(){
        if constexpr(is_same_v<type, float>)        return stof(m_str);
        else if (is_same_v<type, int>)              return stoi(m_str);
    }
};

int n_int = from_string("123");
float n_float = from_string("123.111");
// Will only work with C++17 due to `is_same_v`
```

<!-- wp:paragraph -->
<p>If you are unaware of constexpr, I have written a short post on <a href="http://www.vishalchovatiya.com/when-to-use-const-vs-constexpr-in-cpp/" target="_blank" rel="noreferrer noopener" aria-label="when to use const vs constexpr in c++ (opens in a new tab)"><span style="color:#0015a3" class="color">when to use const vs constexpr in c++</span></a>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>When you use <code><a rel="noreferrer noopener" aria-label="nullptr (opens in a new tab)" href="http://www.vishalchovatiya.com/what-exactly-nullptr-is-in-cpp/" target="_blank"><span style="color:#0002a3" class="color"><strong>nullptr</strong></span></a></code>(introduced in C++11), this is the technique that runs under the hood to deduce the correct type depending upon the pointer variable it is assigning to.  </li><li>You can also overcome the function overloading limitation on the basis of a return type as we have seen above.</li><li>Return Type Resolver can also used to provide a generic interface for <a rel="noreferrer noopener" aria-label="assignment (opens in a new tab)" href="http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/" target="_blank"><span style="color:#1b08ed" class="color">assignment</span></a>, independent of the object assigned to. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="Type-Eraser">3. Type Erasure</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong> To create generic container that can handle a variety of concrete types.<br><strong><em>Implementation: </em></strong>Can be implemented by <code>void*</code>, templates, polymorphism, union, proxy class, etc. <br><strong><em>Also known as: Duck-typing</em></strong> </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Problem</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>C++ is a <a rel="noreferrer noopener" aria-label="statically typed (opens in a new tab)" href="http://www.vishalchovatiya.com/cpp-type-casting-with-example-for-c-developers/" target="_blank"><span style="color:#0d18e5" class="color">statically typed</span></a> language with strong typing. In statically typed languages, object type known &amp; set at compile-time. While in dynamically typed languages the type associated with run-time values.</li><li>In strongly typed languages the type of an object doesn't change after compilation.  </li><li>To overcome this limitation &amp; providing a feature like dynamically typed languages, library designers come up with various generic container kind of things like <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://en.cppreference.com/w/cpp/utility/any" target="_blank"><span style="color:#0b0ee7" class="color">std::any</span></a></code>(C++17), <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://en.cppreference.com/w/cpp/utility/variant" target="_blank"><span style="color:#0d24f2" class="color">std::variant</span></a></code> (C++17), <code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://en.cppreference.com/w/cpp/utility/functional/function" target="_blank"><span style="color:#1a29f7" class="color">std::function</span></a></code>(C++11), etc.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Different Type Erasure Techniques</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>There is no one strict rule on how to implement this idiom, it can have various forms with its own drawbacks as follows: </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>=> Type erasure using void* (like in C)</strong></p>
<!-- /wp:paragraph -->

```c++
void qsort (void* base, size_t num, size_t size,
            int (*compare)(const void*,const void*));
```

<!-- wp:paragraph -->
<p><em>Drawback:</em> not safe &amp; separate compare function needed for each type</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>=> Type erasure using templates</strong></p>
<!-- /wp:paragraph -->

```c++
template <class RandomAccessIterator>
  void sort(RandomAccessIterator first, RandomAccessIterator last);
```

<!-- wp:paragraph -->
<p><em>Drawback:</em> may lead to many function template instantiations &amp; longer compilation time</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>=> Type erasure using polymorphism</strong></p>
<!-- /wp:paragraph -->

```c++
struct base { virtual void method() = 0; };
struct derived_1 : base { void method() { cout << "derived_1\n"; } };
struct derived_2 : base { void method() { cout << "derived_2\n"; } };
// We don't see a concrete type (it's erased) though can dynamic_cast
void call(base* ptr) { ptr->method(); };
```

<!-- wp:paragraph -->
<p><em>Drawback:</em> run-time cost (dynamic dispatch, indirection, vtable, etc.)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>=> Type erasure using union</strong></p>
<!-- /wp:paragraph -->

```c++
struct Data {};
union U {
    Data d;         // occupies 1 byte
    std::int32_t n; // occupies 4 bytes
    char c;         // occupies 1 byte
    ~U() {}         // need to know currently active type
}; // an instance of U in total occupies 4 bytes.
```

<!-- wp:paragraph -->
<p><em>Drawback:</em> not <a rel="noreferrer noopener" aria-label="type-safe (opens in a new tab)" href="http://www.vishalchovatiya.com/cpp-type-casting-with-example-for-c-developers/" target="_blank"><span style="color:#210fe7" class="color">type-safe</span></a></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As I mentioned earlier that standard library already has such generic containers.</li><li>To understand type erasure better let's implement one like <code>std::any</code>:</li></ul>
<!-- /wp:list -->

```c++
struct any 
{
    struct base {};
    
    template<typename T>
    struct inner: base{
        inner(T t): m_t{std::move(t)} {}
        T m_t;
        static void type() {}
    };
    
    any(): m_ptr{nullptr}, typePtr{nullptr} {}
    template<typename T>
    any(T && t): m_ptr{std::make_unique<inner<T>>(t)}, typePtr{&inner<T>::type} {}
    template<typename T>
    any& operator=(T&& t){
        m_ptr = std::make_unique<inner<T>>(t); 
        typePtr = &inner<T>::type;
        return *this;
    }
private:
    template<typename T>
    friend T& any_cast(const any& var);
    
    std::unique_ptr<base> m_ptr = nullptr;
    void (*typePtr)() = nullptr;
};
template<typename T>
T& any_cast(const any& var)
{
    if(var.typePtr == any::inner<T>::type)
        return static_cast<any::inner<T>*>(var.m_ptr.get())->m_t;
    throw std::logic_error{"Bad cast!"};
}
int main()
{
    any var(10);
    std::cout << any_cast<int>(var) << std::endl;
    var = std::string{"some text"};
    std::cout << any_cast<std::string>(var) << std::endl;
    return 0;
}
```

<!-- wp:paragraph -->
<p>Especially, the thing here to note is how we are leveraging empty static method i.e. <code>inner&lt;T&gt;::type()</code> to determine template instance type in <code>any_cast&lt;T&gt;</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Employ to handle multiple types of the return value from function/method(Although that's not recommended advice).</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="CRTP">4. CRTP</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong> To achieve static polymorphism.<br><strong><em>Implementation: </em></strong>Make use of base class template spcialization. <br><strong><em>Also known as: </em></strong>Upside-down inheritance, Static polymorphism </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Problem </h4>
<!-- /wp:heading -->

```c++
struct obj_type_1
{
    bool operator<(const value &rhs) const {return m_x < rhs.m_x;}
    // bool operator==(const value &rhs) const;
    // bool operator!=(const value &rhs) const;    
    // List goes on. . . . . . . . . . . . . . . . . . . .
private:
    // data members to compare
};

struct obj_type_2
{
    bool operator<(const value &rhs) const {return m_x < rhs.m_x;}
    // bool operator==(const value &rhs) const;
    // bool operator!=(const value &rhs) const;    
    // List goes on. . . . . . . . . . . . . . . . . . . .
private:
    // data members to compare
};

struct obj_type_3 { ...
struct obj_type_4 { ...
// List goes on. . . . . . . . . . . . . . . . . . . .
```

<!-- wp:list -->
<ul><li>For each comparable objects, you need to define respective comparison operators. This is redundant because if we have an <code>operator &lt;</code> , we can overload other operators on the basis of it. </li><li>Thus, <code>operator &lt;</code> is the only one operator having type information, other operators can be made type independent for reusability purpose.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>C</strong>uriously <strong>R</strong>ecurring <strong>T</strong>emplate <strong>P</strong>attern implementation rule is simple, <strong><em>separate out the type-dependent &amp; independent functionality and bind type</em> <em>independent functionality with the base class using template specialization</em></strong>. </li><li>Above line may seem cryptic at first. So, consider the below solution to the above problem for more clarity:</li></ul>
<!-- /wp:list -->

```c++
template<class derived>
struct compare {};
struct value : public compare<value> 
{
    value(const int x): m_x(x) {}
    bool operator<(const value &rhs) const { return m_x < rhs.m_x; }
private:
    int m_x;
};

template <class derived>
bool operator>(const compare<derived> &lhs, const compare<derived> &rhs) {
    // static_assert(std::is_base_of_v<compare<derived>, derived>); // Compile time safety measures
    return (static_cast<const derived&>(rhs) < static_cast<const derived&>(lhs));
}

/*  Same goes with other operators
 == :: returns !(lhs < rhs) and !(rhs < lhs)
 != :: returns !(lhs == rhs)
 >= :: returns (rhs < lhs) or (rhs == lhs)
 <= :: returns (lhs < rhs) or (rhs == lhs) 
*/

int main()
{   
    value v1{5}, v2{10};
    cout <<boolalpha<< "v1 == v2: " << (v1 > v2) << '\n';
    return 0;
}
// Now no need to write comparator operators for all the classes, 
// Write only type dependent `operator <` &  use CRTP
```

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>CRTP widely employed for static polymorphism without bearing the cost of virtual dispatch mechanism. Consider the following code we have not used virtual keyword &amp; still achieved the functionality of polymorphism(specifically static polymorphism).</li></ul>
<!-- /wp:list -->

```c++
template<typename specific_animal>
struct animal {
    void who() { implementation().who(); }
private:
    specific_animal& implementation() {return *static_cast<specific_animal*>(this);}
};

struct dog : public animal<dog> {
    void who() { cout << "dog" << endl; }
};

struct cat : public animal<cat> {
    void who() { cout << "cat" << endl; }
};

template<typename specific_animal>
void who_am_i(animal<specific_animal> & animal) {
    animal.who();
}
```

<!-- wp:list -->
<ul><li>CRTP can also used for optimization as we have seen above it also enables code reusability.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Update: The above hiccup of declaring multiple comparisons operator will permanently be sorted from C++20 by using <a rel="noreferrer noopener" aria-label="spaceship (opens in a new tab)" href="https://en.cppreference.com/w/cpp/language/default_comparisons" target="_blank"><span style="color:#0007a3" class="color">spaceship</span></a>(<code>&lt;=&gt;</code>)/<a rel="noreferrer noopener" aria-label="Three-way-comparison operator (opens in a new tab)" href="https://en.wikipedia.org/wiki/Three-way_comparison" target="_blank"><span style="color:#1c00a3" class="color">Three-way-comparison operator</span></a>.  </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="Virtual-Constructor">5. Virtual Constructor</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong>  To create a copy or new object without knowing its concrete type. <br><strong><em>Implementation: </em></strong>Exploits overloaded methods with polymorphic assignment. <br><strong><em>Also known as: </em></strong>Factory method/design-pattern. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Problem</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>C++ has the support of polymorphic object destruction using it's base class's <a rel="noreferrer noopener" aria-label="virtual destructor (opens in a new tab)" href="http://www.vishalchovatiya.com/part-3-all-about-virtual-keyword-in-c-how-virtual-destructor-works/" target="_blank"><span style="color:#1c37e5" class="color">virtual destructor</span></a>.  Equivalent support for creation and copying of objects is missing as С++ doesn't support virtual constructor, <a rel="noreferrer noopener" aria-label="copy constructors (opens in a new tab)" href="http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/" target="_blank"><span style="color:#0a07f0" class="color">copy constructors</span></a>. </li><li>Moreover, you can’t create an object unless you know its static type, because the compiler must know the amount of space it needs to allocate. For the same reason, copy of an object also requires its type to known at compile-time.  </li></ul>
<!-- /wp:list -->

```c++
struct animal {
    virtual ~animal(){ cout<<"~animal\n"; }
};

struct dog : animal {
    ~dog(){ cout<<"~dog\n"; }
};

struct cat : animal {
    ~cat(){ cout<<"~cat\n"; }
};

void who_am_i(animal *who) { // not sure whether dog would be passed here or cat
    // How to `create` the object of same type i.e. pointed by who ?
    // How to `copy` object of same type i.e. pointed by who ?
    delete who; // you can delete object pointed by who
}
```

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>The Virtual Constructor technique allows polymorphic creation &amp; copying of objects in C++ by delegating the act of creation &amp; copying the object to the derived class through the use of virtual methods. </li><li>Following code is not only implement virtual constructor(i.e. <code>create()</code>) but also implements virtual <a rel="noreferrer noopener" aria-label="copy constructor (opens in a new tab)" href="http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp-with-example/" target="_blank"><span style="color:#0e0aeb" class="color">copy constructor</span></a> (i.e. <code>clone()</code>) .</li></ul>
<!-- /wp:list -->

```c++
struct animal {
    virtual ~animal() = default;
    virtual std::unique_ptr<animal> create() = 0;
    virtual std::unique_ptr<animal> clone() = 0;
};

struct dog : animal {
    std::unique_ptr<animal> create() { return std::make_unique<dog>(); }
    std::unique_ptr<animal> clone() { return std::make_unique<dog>(*this); }
};

struct cat : animal {
    std::unique_ptr<animal> create() { return std::make_unique<cat>(); }
    std::unique_ptr<animal> clone() { return std::make_unique<cat>(*this); }
};

void who_am_i(animal *who) {
    auto new_who = who->create();// `create` the object of same type i.e. pointed by who ?
    auto duplicate_who = who->clone(); // `copy` object of same type i.e. pointed by who ?    
    delete who; // you can delete object pointed by who
}
```

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>To provide a generic interface to produce/copy a variety of classes using only one class.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="SFINAE-&amp;-std::enable_if">6. SFINAE and std::enable_if</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong> To filter out&nbsp;functions that do not yield valid template instantiations from a set of overloaded functions. <br><strong><em>Implementation: </em></strong>Achieved automatically by compiler or exploited using std::enable_if. <br><strong><em>Also known as: </em></strong> </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Motivation</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>S</strong>ubstitution&nbsp;<strong>F</strong>ailure&nbsp;<strong>I</strong>s&nbsp;<strong>N</strong>ot&nbsp;<strong>A</strong>n&nbsp;<strong>E</strong>rror is a language feature(not an idiom) a C++ compiler uses to filter out some templated function overloads during overload resolution. </li><li>During overload resolution of function templates, when substituting the explicitly specified or deduced type for the template parameter fails, the specialization discarded from the overload set instead of causing a compile error.</li><li>Substitution failure happens when type or expression is ill-formed.</li></ul>
<!-- /wp:list -->

```c++
template<class T>
void func(T* t){ // Single overload set
    if constexpr(std::is_class_v<T>){ cout << "T is user-defined type\n"; }
    else { cout << "T is primitive type\n"; }
}

int primitive_t = 6;
struct {char var = '4';} class_t;


func(&class_t);
func(&primitive_t);
```

<!-- wp:list -->
<ul><li>How can we create two sets(based on primitive type &amp; user-defined type separately) of a function having the same signature?</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Solution</h4>
<!-- /wp:heading -->

```c++
template<class T, typename = std::enable_if_t<std::is_class_v<T>>>
void func(T* t){
    cout << "T is user-defined type\n";
}
 
template<class T, std::enable_if_t<std::is_integral_v<T>, T> = 0>
void func(T* t){ // NOTE: function signature is NOT-MODIFIED
    cout << "T is primitive type\n";
}
```

<!-- wp:list -->
<ul><li>Above code snippet is a short example of exploiting SFINAE using   <code>std::enable_if</code>, in which first template instantiation will become equivalent to <code>void func&lt;(anonymous), void&gt;((anonymous) * t)</code> and second, <code>void func(int * t)</code>. </li><li>You can read more above <code>std::enable_if</code>  <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="https://en.cppreference.com/w/cpp/types/enable_if" target="_blank"><span style="color:#0e23de" class="color">here</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Together with <code>std::enable_if</code>, SFINAE is heavily used in template metaprogramming.  </li><li>The standard library also leveraged SFINAE in most <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://en.cppreference.com/w/cpp/header/type_traits" target="_blank"><span style="color:#280ce0" class="color">type_traits</span></a> utilities. Consider the following:</li></ul>
<!-- /wp:list -->

```c++
// Stolen & trimmed from https://stackoverflow.com/questions/982808/c-sfinae-examples.
template<typename T>
class is_class_type {
    template<typename C> static char test(int C::*);    
    template<typename C> static double test(...);
public:
    enum { value = sizeof(is_class_type<T>::test<T>(0)) == sizeof(char) };
};

struct class_t{};

int main()
{
    cout<<is_class_type<class_t>::value<<endl;    // 1
    cout<<is_class_type<int>::value<<endl;        // 0
    return 0;
}
```

<!-- wp:list -->
<ul><li>Without SFINAE, you would get a compiler error, something like "<code>0</code> cannot be converted to member pointer for non-class type <code>int</code>" as both the overload of <code>test</code> only differs in terms of the return type. </li><li>Because <code>int</code> is not a class, so it can't have a member pointer of type&nbsp;<code>int int::*</code>&nbsp;. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="Temporary-Proxy">7. Proxy</h3>
<!-- /wp:heading -->

<!-- wp:paragraph {"backgroundColor":"very-light-gray"} -->
<p class="has-background has-very-light-gray-background-color"><strong><em>Intent:</em></strong> To achieve intuitive functionality using middleware class.<br><strong><em>Implementation: </em></strong>By use of temporary/proxy class. <br><strong><em>Also known as: </em></strong> <code>operator []</code>(i.e. subscript)&nbsp;proxy, double/twice operator overloading </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Motivation</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Most of the dev believes this is only about the subscript operator (i.e. <code>operator[ ]</code>),  but I believe type that comes in between exchanging data is proxy. </li><li>We have already seen a nice example of this idiom indirectly above in <a href="#Type-Eraser"><span style="color:#0c29e7" class="color">type-erasure</span></a>(i.e. class <code>any::inner&lt;&gt;</code>). But still, I think one more example will add concreteness to our understanding.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>operator [ ] solution</h4>
<!-- /wp:heading -->

```c++
template <typename T = int>
struct arr2D{
private:
    struct proxy_class{
        proxy_class(T *arr) : m_arr_ptr(arr) {}
        T &operator[](uint32_t idx) { return m_arr_ptr[idx]; }
    private:
        T *m_arr_ptr;
    };
    T m_arr[10][10];
public:
    arr2D::proxy_class operator[](uint32_t idx) { return arr2D::proxy_class(m_arr[idx]); }
};

int main()
{
    arr2D<> arr;
    arr[0][0] = 1;
    cout << arr[0][0];
    return 0;
}
```

<!-- wp:heading {"level":4} -->
<h4>Usecases</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>To create intuitive features like double operator overloading, <code>std::any</code> etc.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Summary by FAQs</h3>
<!-- /wp:heading -->

<!-- wp:yoast/faq-block {"questions":[{"id":"faq-question-1573471297401","question":["When to actually use RAII?"],"answer":["When you have set of steps to carry out a task \u0026 two steps are ideal i.e. set-up \u0026 clean-up, then that's the place you can employ RAII."],"jsonQuestion":"When to actually use RAII?","jsonAnswer":"When you have set of steps to carry out a task \u0026amp; two steps are ideal i.e. set-up \u0026amp; clean-up, then that's the place you can employ RAII."},{"id":"faq-question-1573471311358","question":["Why can't functions be overloaded by return type? "],"answer":["You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression. For example, I can just say",{"type":"br","props":{"children":[]}},{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["get_val();"]}},{"type":"br","props":{"children":[]}},{"type":"br","props":{"children":[]}},"What does the compiler do now? "],"jsonQuestion":"Why can't functions be overloaded by return type? ","jsonAnswer":"You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression. For example, I can just say\u003cbr/\u003e\u003cbr/\u003e\u003ccode\u003eget_val();\u003c/code\u003e\u003cbr/\u003e\u003cbr/\u003eWhat does the compiler do now? "},{"id":"faq-question-1573018692712","question":["When to use return type resolver idiom?"],"answer":["You can apply return type resolver idiom when your input types are fixed but output types may vary."],"jsonQuestion":"When to use return type resolver idiom?","jsonAnswer":"You can apply return type resolver idiom when your input types are fixed but output types may vary."},{"id":"faq-question-1573471312117","question":["What is type erasure in C++?"],"answer":["- Type erasure technique is used to design generic type which relies on the type of ",{"type":"a","props":{"rel":"noreferrer noopener","aria-label":"assignment (opens in a new tab)","href":"http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/","target":"_blank","children":[{"type":"span","props":{"style":"color:#0d18e6","class":"color","children":["assignment"]}}]}},"(as we do in python).",{"type":"br","props":{"children":[]}},"- By the way, do you know ",{"type":"code","props":{"children":["auto"]}}," or can you design one now?"],"jsonQuestion":"What is type erasure in C++?","jsonAnswer":"- Type erasure technique is used to design generic type which relies on the type of \u003ca rel=\u0022noreferrer noopener\u0022 aria-label=\u0022assignment (opens in a new tab)\u0022 href=\u0022http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#0d18e6\u0022 class=\u0022color\u0022\u003eassignment\u003c/span\u003e\u003c/a\u003e(as we do in python).\u003cbr/\u003e- By the way, do you know \u003ccode\u003eauto\u003c/code\u003e or can you design one now?"},{"id":"faq-question-1573018709667","question":["Best scenarios to apply type erasure idiom? "],"answer":["- Useful in generic programming.",{"type":"br","props":{"children":[]}},"- Can also be used to handle multiple types of the return value from function/method(Although that's not recommended advice). "],"jsonQuestion":"Best scenarios to apply type erasure idiom? ","jsonAnswer":"- Useful in generic programming.\u003cbr/\u003e- Can also be used to handle multiple types of the return value from function/method(Although that's not recommended advice). "},{"id":"faq-question-1573018802857","question":["What is the curiously recurring template pattern (CRTP)?"],"answer":["CRTP is when a class ",{"type":"code","props":{"children":["A"]}}," has a base class. And that base class is a template specialization for the class ",{"type":"code","props":{"children":["A"]}}," itself. E.g.",{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["template \u003cclass T\u003e  "]}},{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["class X{...}; "]}},{"type":"br","props":{"children":[]}},{"type":"code","props":{"children":["class A : public X\u003cA\u003e {...};"]}},{"type":"br","props":{"children":[]}},"It ",{"type":"em","props":{"children":["is"]}}," curiously recurring, isn't it?"],"jsonQuestion":"What is the curiously recurring template pattern (CRTP)?","jsonAnswer":"CRTP is when a class \u003ccode\u003eA\u003c/code\u003e has a base class. And that base class is a template specialization for the class \u003ccode\u003eA\u003c/code\u003e itself. E.g.\u003cbr/\u003e\u003ccode\u003etemplate \u0026lt;class T\u003e  \u003c/code\u003e\u003cbr/\u003e\u003ccode\u003eclass X{...}; \u003c/code\u003e\u003cbr/\u003e\u003ccode\u003eclass A : public X\u0026lt;A\u003e {...};\u003c/code\u003e\u003cbr/\u003eIt \u003cem\u003eis\u003c/em\u003e curiously recurring, isn't it?"},{"id":"faq-question-1573471495365","question":["Why Curiously Recurring Template Pattern (CRTP) works?"],"answer":["I think ",{"type":"a","props":{"href":"https://stackoverflow.com/questions/49708984/why-curiously-recurring-template-pattern-crtp-works","target":"_blank","rel":"noreferrer noopener","aria-label":"this (opens in a new tab)","children":[{"type":"span","props":{"style":"color:#2100a3","class":"color","children":["this"]}}]}}," answer is very appropriate."],"jsonQuestion":"Why Curiously Recurring Template Pattern (CRTP) works?","jsonAnswer":"I think \u003ca href=\u0022https://stackoverflow.com/questions/49708984/why-curiously-recurring-template-pattern-crtp-works\u0022 target=\u0022_blank\u0022 rel=\u0022noreferrer noopener\u0022 aria-label=\u0022this (opens in a new tab)\u0022\u003e\u003cspan style=\u0022color:#2100a3\u0022 class=\u0022color\u0022\u003ethis\u003c/span\u003e\u003c/a\u003e answer is very appropriate."},{"id":"faq-question-1573020210693","question":["What is  SFINAE?"],"answer":[{"type":"strong","props":{"children":["S"]}},"ubstitution ",{"type":"strong","props":{"children":["F"]}},"ailure ",{"type":"strong","props":{"children":["I"]}},"s ",{"type":"strong","props":{"children":["N"]}},"ot ",{"type":"strong","props":{"children":["A"]}},"n ",{"type":"strong","props":{"children":["E"]}},"rror is a language feature(not an idiom) a C++ compiler uses to filter out some templated function overloads during overload resolution. "],"jsonQuestion":"What is  SFINAE?","jsonAnswer":"\u003cstrong\u003eS\u003c/strong\u003eubstitution \u003cstrong\u003eF\u003c/strong\u003eailure \u003cstrong\u003eI\u003c/strong\u003es \u003cstrong\u003eN\u003c/strong\u003eot \u003cstrong\u003eA\u003c/strong\u003en \u003cstrong\u003eE\u003c/strong\u003error is a language feature(not an idiom) a C++ compiler uses to filter out some templated function overloads during overload resolution. "},{"id":"faq-question-1573401601882","question":[" What is Proxy Class in C++?"],"answer":["A proxy is a class that provides a modified interface to another class. "],"jsonQuestion":" What is Proxy Class in C++?","jsonAnswer":"A proxy is a class that provides a modified interface to another class. "},{"id":"faq-question-1573401602741","question":["Why do we not have a virtual constructor in C++?"],"answer":["- A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an object is created of such class, it contains a 'virtual-pointer' which points to the base of the corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address. ",{"type":"br","props":{"children":[]}},"- A constructor can not be virtual, because when the constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual. "],"jsonQuestion":"Why do we not have a virtual constructor in C++?","jsonAnswer":"- A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an object is created of such class, it contains a 'virtual-pointer' which points to the base of the corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address. \u003cbr/\u003e- A constructor can not be virtual, because when the constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual. "},{"id":"faq-question-1573471723269","question":["Can we make a class copy constructor virtual in C++?"],"answer":["Similar to \u0022Why do we not have a virtual constructor in C++?\u0022 which already answered above."],"jsonQuestion":"Can we make a class copy constructor virtual in C++?","jsonAnswer":"Similar to \u0022Why do we not have a virtual constructor in C++?\u0022 which already answered above."},{"id":"faq-question-1573018796284","question":["What are the use cases \u0026 need for virtual constructor?"],"answer":["To create \u0026 copy the object(without knowing its concrete type) using a base class polymorphic method. "],"jsonQuestion":"What are the use cases \u0026amp; need for virtual constructor?","jsonAnswer":"To create \u0026amp; copy the object(without knowing its concrete type) using a base class polymorphic method. "}]} -->
<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section"><strong class="schema-faq-question">When to actually use RAII?</strong> <p class="schema-faq-answer">When you have set of steps to carry out a task &amp; two steps are ideal i.e. set-up &amp; clean-up, then that's the place you can employ RAII.</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">Why can't functions be overloaded by return type? </strong> <p class="schema-faq-answer">You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression. For example, I can just say<br/><br/><code>get_val();</code><br/><br/>What does the compiler do now? </p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">When to use return type resolver idiom?</strong> <p class="schema-faq-answer">You can apply return type resolver idiom when your input types are fixed but output types may vary.</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">What is type erasure in C++?</strong> <p class="schema-faq-answer">- Type erasure technique is used to design generic type which relies on the type of <a rel="noreferrer noopener" aria-label="assignment (opens in a new tab)" href="http://www.vishalchovatiya.com/2-wrong-way-to-learn-copy-assignment-operator-in-cpp-with-example/" target="_blank"><span style="color:#0d18e6" class="color">assignment</span></a>(as we do in python).<br/>- By the way, do you know <code>auto</code> or can you design one now?</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">Best scenarios to apply type erasure idiom? </strong> <p class="schema-faq-answer">- Useful in generic programming.<br/>- Can also be used to handle multiple types of the return value from function/method(Although that's not recommended advice). </p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">What is the curiously recurring template pattern (CRTP)?</strong> <p class="schema-faq-answer">CRTP is when a class <code>A</code> has a base class. And that base class is a template specialization for the class <code>A</code> itself. E.g.<br/><code>template &lt;class T>  </code><br/><code>class X{...}; </code><br/><code>class A : public X&lt;A> {...};</code><br/>It <em>is</em> curiously recurring, isn't it?</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">Why Curiously Recurring Template Pattern (CRTP) works?</strong> <p class="schema-faq-answer">I think <a href="https://stackoverflow.com/questions/49708984/why-curiously-recurring-template-pattern-crtp-works" target="_blank" rel="noreferrer noopener" aria-label="this (opens in a new tab)"><span style="color:#2100a3" class="color">this</span></a> answer is very appropriate.</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">What is  SFINAE?</strong> <p class="schema-faq-answer"><strong>S</strong>ubstitution <strong>F</strong>ailure <strong>I</strong>s <strong>N</strong>ot <strong>A</strong>n <strong>E</strong>rror is a language feature(not an idiom) a C++ compiler uses to filter out some templated function overloads during overload resolution. </p> </div> <div class="schema-faq-section"><strong class="schema-faq-question"> What is Proxy Class in C++?</strong> <p class="schema-faq-answer">A proxy is a class that provides a modified interface to another class. </p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">Why do we not have a virtual constructor in C++?</strong> <p class="schema-faq-answer">- A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an object is created of such class, it contains a 'virtual-pointer' which points to the base of the corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address. <br/>- A constructor can not be virtual, because when the constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual. </p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">Can we make a class copy constructor virtual in C++?</strong> <p class="schema-faq-answer">Similar to "Why do we not have a virtual constructor in C++?" which already answered above.</p> </div> <div class="schema-faq-section"><strong class="schema-faq-question">What are the use cases &amp; need for virtual constructor?</strong> <p class="schema-faq-answer">To create &amp; copy the object(without knowing its concrete type) using a base class polymorphic method. </p> </div> </div>
<!-- /wp:yoast/faq-block -->

## You may like these also

- [21 new features of Modern C++ to use in your project](https://dev.to/visheshpatel/21-new-features-of-modern-c-to-use-in-your-project-3f87)
- [All about lambda functions in C++(from C++11 to C++17)](https://dev.to/visheshpatel/all-about-lambda-function-in-c-from-c-11-to-c-17-3p5h)
- [7 Best Practices For Exception Handling In Modern C++](https://dev.to/visheshpatel/7-best-practices-for-exception-handling-in-modern-c-10ia)

[Have any suggestions, query or wants to say `Hi`? Take the Pressure Off, you are just a click away.](http://www.vishalchovatiya.com/contact-2/)🖱️