使用具有相同成员函数名称的 CRTP

Rya*_*yan 2 c++ inheritance crtp

当我看到使用的 CRTP 模式时,似乎在基类型中调用的函数名称总是指向派生类型中不同名称的实现函数(例如:foo()in base 进行调用static_cast<DerivedType*>(this)->foo_implementation();.

有没有办法使用相同的函数名来实现 CRTP 模式?我有一个较长的继承链,其中函数可能在链的第一级没有具体实现,因此必须使用不同的函数名称不是很干净/可读。

我想要有如下的东西:

template <typename SecondType>
struct FirstType {

    void foo() {
        static_cast<SecondType*>(this)->foo();
    }

};

template <typename ThirdType>
struct SecondType : FirstType<SecondType> {

    void foo() {
        static_cast<ThirdType*>(this)->foo();
    }

};

struct ThirdType : SecondType<ThirdType> {

    void foo() {
        // Concrete implementation here
    }

};
Run Code Online (Sandbox Code Playgroud)

当然,编译器不会抱怨这一点,但我想它会导致隐式 vtable 查找(尽管关键字virtual没有出现),从而违背了使用 CRTP 的目的。

Que*_*tin 5

您可以很好地为这两个函数使用相同的名称,它会正常工作。

使用不同名称的优点是,未能在派生类中实现该函数将导致编译器错误,而不是无限递归和运行时可能的堆栈溢出。