【问题标题】:g++ goes too far when compilingg++ 在编译时走得太远了
【发布时间】:2013-09-17 02:31:19
【问题描述】:

我正在尝试使用递归模板在 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 语句,也会评估相同的错误。为什么没有动态检查作用域和成员函数以及为什么编译器会忽略return

【问题讨论】:

  • 因为模板是纯粹的编译时构造。

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


【解决方案1】:

模板是纯粹的编译时构造。它们只是指示编译器生成类或函数,然后正常编译(因此它们必须在语法上有效,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

【讨论】:

    【解决方案2】:

    不管提早返回,编译器都会扩行

    class T::Base *V;
    

    递归。如果你想阻止编译器永远扩展模板(或者直到编译器打破一些内部限制,以先到者为准:-))你需要在编译时进行调度。也许这样的事情会奏效。将您的 printStackTrace 函数更改为

    template <class T>
    void printStackTrace(T* c) {
        printStackTraceImpl(c, std::is_same<T, StackTrace>);
    }
    
    template <class T>
    void printStackTraceImpl(T* c, std::true_type) { 
          cout << typeid(T).name() << "." << endl;
          class T::Base *V;
          printStackTrace(V);
    }
    
    template <class T>
    void printStackTraceImpl(T* c, std::false_type) { 
        // do nothing.
    }
    

    编辑:或按照其他地方的建议,为 StackTrace 类型提供重载。这实际上比我未经测试的代码干净得多:-)

    【讨论】:

    • 为什么都是std::conditional?如果你有 C++11,只需使用std::is_same
    • 非常正确。更新。不知道为什么我这么快就伸手去拿重型枪,哈哈。
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    相关资源
    最近更新 更多