While I was trying to understand CRTP, I came across this example, where it is a bit fuzzy to me. I can achieve the same results if I do something simpler like this:
#pragma once
#include <iostream>
template <typename T>
class Base
{
public:
    void method() {
        static_cast<T*>(this)->method();
    }
};
class Derived1 // : public Base<Derived1>   <-- commented inherintance
{
public:
    void method() {
        std::cout << "Derived1 method" << std::endl;
    }
};
class Derived2 // : public Base<Derived2>   <-- commmented inherintance
{
public:
    void method() {
        std::cout << "Derived2 method" << std::endl;
    }
};
#include "crtp.h"
int main()
{
    Derived1 d1;
    Derived2 d2;
    d1.method();
    d2.method();
    return 0;
}
My question is: what is the purpose of CRTP here? After thought a bit I guess this use is to allow something like this:
template<typename T>
void call(Base<T>& x)
{
    x.method();
}
and call it like this
int main()
{
    Derived1 d1;
    Derived2 d2;
   call(d1);
   call(d2)
}
Am I correct?
Aucun commentaire:
Enregistrer un commentaire