有沒有什麼方法可以通過使用CTRP來爲繼承關係中的類定義一個同名的類型?我嘗試了下面的代碼,但從clang++
得到error: member 'ptr_t' found in multiple base classes of different types
。當使用繼承時,使用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 2012-02-02 16:18:50