c++ - 模板代码上的编译器堆栈溢出

标签 c++ templates visual-c++ visual-c++-2010

在处理我自己的类型删除迭代器时,我遇到了一个问题,即编译器 (MSVC10) 因这段代码的堆栈溢出而崩溃:

struct base {};  //In actual code, this is a template struct that holds data
template<class category, class valuetype>  
    struct any;  //In actual code, this is abstract base struct
template<class basetype, class category, class valuetype> 
    struct from; //In actual code, this is function definitions of any

template<class valuetype>
struct any<void,valuetype>
{ void a() {} };
template<class category, class valuetype>  
struct any
    : public any<void,valuetype> //commenting this line makes it compile
{ void b() {} };        

template<class basetype, class valuetype>
struct from<basetype,void,valuetype>
    : public base  //commenting out _either_ of these makes it compile
    , public any<void,valuetype>
{ void c() {} };

int main() {
    from<int, void, char> a;
    a.a();
    a.c();
    any<int, char> b;
    b.a();
    b.b();
    return 0;
}

很明显,我已经删除了 bug 仍然存在的所有内容。 (原始代码有 780 多行)删除任何剩余的模板参数会导致代码编译。

完整的错误信息是:

main.cpp(23): fatal error C1063: compiler limit : compiler stack overflow
    main.cpp(20) : see reference to class template instantiation 'from<basetype,void,valuetype>' being compiled

IDEOne compiles it fine .我听说 MSVC 错误地实现了两阶段查找,这似乎是相关的,但并没有解释为什么当我删除使 from inherit from base 的行时它会编译. 谁能教我为什么 MSVC10 不能编译它?我做了哪些我应该避免的事情?

最佳答案

作为变通方法,考虑在未特化的 any 和特化的 category = void 之间引入一个额外的类:

template <class valuetype>
class detail_void_any
    : public any<void, valuetype>
{
};


template<class category, class valuetype>
class any
    : public detail_void_any<valuetype>
{
};

下面的完整程序应该编译无误:

class base {};      // Data Holder (in reality it's templated, so required)
template<class category, class valuetype>  
        class any;  // Virtual Function Interface
template<class basetype, class category, class valuetype> 
        class from; // Virtual Function Implementation

template<class valuetype>
class any<void,valuetype>
{};


template <class valuetype>
class detail_void_any
    : public any<void, valuetype>
{
};

template<class category, class valuetype>
class any
    : public detail_void_any<valuetype>
{
};

template<class basetype, class valuetype>
class from<basetype,void,valuetype>
        : public base  //commenting out _either_ of these makes it compile
        , public any<void,valuetype>
{}; //this is line 23, where the compiler crashes

int main() {return 0;}

关于c++ - 模板代码上的编译器堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496029/

相关文章:

c++ - OpenMP 为内联函数声明 SIMD

C++ 错误 : assignment of read-only variable

c++ - 如何在Arduino-ESP8266上从C/C++中的字符串解析time_t?

c++ - C++ 中的维动态数组

c++ - 可以接受函数指针或 Functor 的模板参数

c++ - 模板函数包装器

c++ - C++ 中的错误 C3867

html - Angular 2。如何在模板中打印来自 @Input() 参数的 HTML 标签?

c++ - 更改类的私有(private)成员

c++ - 我可以在 C++ 中创建强类型整数吗?