有什么方法可以使用CTRP为继承关系中的类定义同名的类型吗?我尝试了以下代码,但是 error: member 'ptr_t' found in multiple base classes of different types
来自 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;
}
下面的当然可以(但是多余,违背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 实现此行为,为什么禁止这样做?
最佳答案
您的问题与 CRTP 无关,而与多重继承有关。 Child
继承ptr_t
来自它的两个基类,并且两种类型都不同:shared_ptr<Parent>
与 shared_ptr<Child>
.因此,编译器无法确定您所说的 Child::ptr_t
是哪种类型。在 main
.
正如您所指出的,您必须使用 typedef
手动修复此问题在 Child
(虽然使您的 Pointable
基类无用)。
class Child : public Parent,
public Pointable<Child> {
public:
typedef Pointable<Child>::ptr_t ptr_t;
关于c++ - 使用继承时,带有 CRTP 的 typedef 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9114959/