c++ - 使用继承时,带有 CRTP 的 typedef 不起作用

标签 c++ inheritance crtp

有什么方法可以使用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/

相关文章:

javascript - 继承和模块模式

c++ - 什么是奇怪的重复模板模式 (CRTP)?

C++:什么是 Curiously-Recurring-Template-Pattern? Curiously-Recurring-Template-Pattern 可以替代虚函数吗?

java - 在派生类中重写基类方法

java - 为什么我没有正确捕获这个异常?

c++ - 迭代不同的 CRTP 派生类方法

c++ - 绘制 gl 场景时 CPU 使用率高;起源?

c++ - 何时在函数调用中使用 move

c++ - 编译器如何将类的对象实例翻译成二进制机器代码?

c++ - VS2010中的单元测试