c++ - 保护 CRTP 模式免受 "pure virtual"调用中的堆栈溢出

标签 c++ crtp pure-virtual virtual-functions

考虑以下标准 CRTP 示例:

#include <iostream>

template<class Derived>
struct Base {
    void f() { static_cast<Derived *>(this)->f(); }
    void g() { static_cast<Derived *>(this)->g(); }
};

struct Foo : public Base<Foo> {
    void f() { std::cout << 42 << std::endl; }
};

int main() {
    Foo foo;
    foo.f(); // just OK
    foo.g(); // this will stack overflow and segfault
}

如果这是常规的虚拟继承,我可以标记虚拟 fg方法一样纯粹

struct Base {
    virtual void f() = 0;
    virtual void g() = 0;
};

并得到一个关于 Foo 的编译时错误是抽象的。但是 CRTP 没有提供这样的保护。我可以以某种方式实现它吗?运行时检查也是可以接受的。我想过比较this->f带有 static_cast<Derived *>(this)->f 的指针,但没能成功。

最佳答案

你可以在编译时断言两个指向成员函数的指针是不同的,例如:

template<class Derived>
struct Base {
    void g() {
        static_assert(&Derived::g != &Base<Derived>::g,
                      "Derived classes must implement g()."); 
        static_cast<Derived *>(this)->g(); 
    }
};

关于c++ - 保护 CRTP 模式免受 "pure virtual"调用中的堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45163209/

相关文章:

c++ - 如果未在 phpmyadmin/linux mysql 客户端中完成,则 INSERT 不起作用

c++ - Pthread 卡住标准输出?

c++ - 为纯虚析构函数添加定义的目的是什么?

c++ - 带有实现的纯虚函数

c++ - 信件取出

python - 如何使用 Fast-Downward 编译 OpenCV

c++ - 结构根据空基类顺序更改大小

c++ - 带有破坏操作的侵入式引用计数

C++模板代码顺序解析/CRTP

c++ - boost 多索引容器,具有纯虚函数的类