Is there any ways to define a type with a same name for classes in inheritance relationship by using CTRP? I tried the following code but got error: member 'ptr_t' found in multiple base classes of different types from clang++.
#include <iostream>
#include <tr1/memory>
template <typename T> class Pointable {
public:
// define a type `ptr_t` in the 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 Child : 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());
return 0;
}
Of course, the following one is OK (but it’s redundant and go against the 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 Child : 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 is no ways to achieve this behavior by using CRTP, why that is prohibited?
Your problem has nothing to do with the CRTP, but with multiple inheritance.
Childinheritsptr_tfrom both its base classes, and both types are different:shared_ptr<Parent>vs.shared_ptr<Child>. Therefore, the compiler cannot figure out which type you mean byChild::ptr_tinmain.As you pointed out, you have to fix this manually using a
typedefinChild(making yourPointablebase class useless, though).