c++ - g++ 在编译时走得太远

标签 c++ templates g++ static-compilation

我正在尝试使用递归模板在 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;
}

Live example

关于c++ - g++ 在编译时走得太远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768759/

相关文章:

c++ - 使用函数参数的模板参数编写函数

c++ - sizeof能否返回0(零)

c++ - volatile 成员不能被成员函数访问

c++ - 使用 VS2015 更改应用程序的入口点

c++ - 模板参数 '(type)0' 与 'EnumValue' 不匹配

c++ - 简单 C++ 'Hello World' 程序执行时间长

c++ - C++ 标准是否对 vector 赋值函数或构造函数有明确的要求?

c++ - 如何在两个 Lua 脚本之间共享数据

c++ - Variadic 模板参数顺序问题

c++模板特征——编译时不包含头文件