- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用递归模板在 C++ 中实现非常简单的单继承堆栈跟踪:
#include <iostream>
using namespace std;
template <class C> struct MakeAlias : C{ typedef C Base; };
class StackTrace{
public:
static int var;
virtual ~StackTrace() {}
template <class T> void printStackTrace(T* c){
if(typeid(T)==typeid(StackTrace))return;
cout << typeid(T).name() << "." << endl;
class T::Base *V;
printStackTrace(V);
}
};
class A : public MakeAlias<StackTrace>{
};
class B : public MakeAlias<A>{
};
class C : public MakeAlias<B>{
public:
void hello(){
cout << "hello from ";
StackTrace::printStackTrace(this);
cout << endl;
}
};
int main(){
C c;
c.hello();
}
一切都应该没问题,但是当我尝试编译它时,g++ 忽略了
if(typeid(T)==typeid(StackTrace))return; 行并返回以下错误:
st.cpp: In member function `void StackTrace::printStackTrace(T*) [with T = StackTrace]':
st.cpp:13: instantiated from `void StackTrace::printStackTrace(T*) [with T = A]'
st.cpp:13: instantiated from `void StackTrace::printStackTrace(T*) [with T = B]'
st.cpp:13: instantiated from `void StackTrace::printStackTrace(T*) [with T = C]'
st.cpp:24: instantiated from here
st.cpp:12: error: no type named `Base' in `class StackTrace'
st.cpp:13: error: no type named `Base' in `class StackTrace'
它尝试调用 C::Base::Base::Base::Base/StackTrace::Base/类,该类在运行时永远不会被调用。即使我在 printStackTrace 声明之后立即放置 return 语句,也会评估相同的错误。为什么不动态检查范围和成员函数以及为什么编译器忽略返回?
最佳答案
模板是一个纯粹的编译时构造。它们只是指示编译器生成类或函数,然后正常编译(因此它们必须在语法上有效,some special exceptions 除外)。
您可以通过重载 printStackTrace
来解决这个问题:
template <class T>
void printStackTrace(T *c)
{
cout << typeid(T).name() << "." << endl;
typename T::Base *V;
printStackTrace(V);
}
void printStackTrace(StackTrace *c)
{
cout << typeid(StackTrace).name() << "." << endl;
}
关于c++ - g++ 在编译时走得太远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768759/
prometheus 和 node exporter 都使用 chrony 来同步时间。 [root@MiWiFi-R3-srv node_exporter-0.18.1.linux-amd64]#
由于某种原因,当我调整浏览器窗口的大小时,文本字段下方的按钮似乎变得比文本框更宽。有什么想法吗? SCRN: HTML : Title
我的一个 有问题标题。我对所有这些都使用单一样式,但有一个特定的 header 无法正常工作。 [附截图] 这是我的全部源代码: Title
我是一名优秀的程序员,十分优秀!