A question about the crtp(Curiously Recurring Template Pattern)

103 views Asked by At

See the code beblow, I have a question about crtp:

  • foo_aa.name_ is illegal because foo_aa is not an object of class AA(it is an object of class Foo<AA>), it doesn't have a class member called name_. I can understand that.
  • But I don't understand why foo_aa.Name() is legal, because I never define any object of class AA, there is no such variable(name_) in memory, how does the Namefunction assess variable name_?.
  • More specifically, I know the cast is made in function Name. But I don't understand why the cast is valid, bacause there is only one Foo<AA> object and it is just a base class object, how can it be converted to a derived class?
namespace static_poly {

template<typename T>
class Foo {
 public:
  std::string Name() {
    return static_cast<T*>(this)->GetName();
  }
};

class AA : public Foo<AA> {
 public:
  std::string GetName() { name_ = "AA"; return name_; }
  std::string name_;
};

void Test() {
  Foo<AA> foo_aa;
  foo_aa.Name();  // legal
  foo_aa.name_ = "hello";  // illagel
}

}  // static_poly


According to Base to derived conversion, I know a base class object can be converted to a derived class object, but the behavior is undefined, why crtp is ok?

0

There are 0 answers