c++ - typedef with CRTP doesn't work when inheritance is used -
c++ - typedef with CRTP doesn't work when inheritance is used -
is there ways define type same name classes in inheritance relationship using ctrp? tried next code got error: fellow member 'ptr_t' found in multiple base of operations classes of different types
clang++
.
#include <iostream> #include <tr1/memory> template <typename t> class pointable { public: // define type `ptr_t` in class `t` publicly typedef std::tr1::shared_ptr<t> ptr_t; }; class parent : public pointable<parent> { public: parent() { std::cout << "parent created" << std::endl; } ~parent() { std::cout << "parent deleted" << std::endl; } }; class kid : public parent, public pointable<child> { public: child() { std::cout << "child created" << std::endl; } ~child() { std::cout << "child deleted" << std::endl; } }; int main(int argc, char** argv) { child::ptr_t child_ptr(new child()); parent::ptr_t parent_ptr(new parent()); homecoming 0; }
of course, next 1 ok (but it's redundant , go against dry principle).
class parent { public: typedef std::tr1::shared_ptr<parent> ptr_t; parent() { std::cout << "parent created" << std::endl; } ~parent() { std::cout << "parent deleted" << std::endl; } }; class kid : public parent { public: typedef std::tr1::shared_ptr<child> ptr_t; child() { std::cout << "child created" << std::endl; } ~child() { std::cout << "child deleted" << std::endl; } };
if there no ways accomplish behavior using crtp, why prohibited?
your problem has nil crtp, multiple inheritance. child
inherits ptr_t
both base of operations classes, , both types different: shared_ptr<parent>
vs. shared_ptr<child>
. therefore, compiler cannot figure out type mean child::ptr_t
in main
.
as pointed out, have prepare manually using typedef
in child
(making pointable
base of operations class useless, though).
class kid : public parent, public pointable<child> { public: typedef pointable<child>::ptr_t ptr_t;
c++ inheritance crtp
Comments
Post a Comment