CTRP를 사용하여 상속 관계에있는 클래스에 대해 동일한 이름을 가진 유형을 정의하는 방법이 있습니까? 다음 코드를 시도했지만 error: member 'ptr_t' found in multiple base classes of different types
을 clang++
에서 가져 왔습니다.CRTP가있는 typedef가 상속을 사용할 때 작동하지 않습니다.
#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;
}
당연히 다음 중 하나는 정상입니다 (단, 중복되어 DRY 원칙에 위배됩니다).
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;
}
};
CRTP를 사용하여이 동작을 수행 할 수있는 방법이 없다면 그 이유는 무엇입니까?
알아보기. 고마워요! – mooz