【发布时间】:2020-08-13 10:37:06
【问题描述】:
我正在试验 CRTP 并将其与接口混合,但我无法解释为什么该程序会崩溃(在 Clang、GCC 和 MSVC 中)。在最新的 Clang 和 GCC 中,它使用 -Wall、-Wextra 构建时不会发出警告。我的猜测是虚拟方法调用没有解决,但我无法解释原因(如果从接口中删除 GetInt() 不会崩溃)。在我的调试器中,我看到崩溃发生在static_cast<T*>(this)->GetInt() 行。
#include <iostream>
class INode
{
public:
virtual int GetInt() = 0;
protected:
~INode() {}
};
template<template<class> typename NodeBase>
class Node : public INode, public NodeBase<Node<NodeBase>>
{
public:
int GetInt() override { return 42; }
};
template<typename T>
class MyNodeBase
{
public:
int CallGetInt() {
return static_cast<T*>(this)->GetInt();
}
};
template<template<class> typename NodeBase>
int Foo1(Node<NodeBase> n) {
return n.CallGetInt();
}
template<typename T>
int Foo2(MyNodeBase<T> n) {
return n.CallGetInt();
}
int main() {
Node<MyNodeBase> n;
std::cout << Foo1(n) << std::endl; // ok
std::cout << Foo2(n) << std::endl; // crash
}
【问题讨论】: