Subclassed STL list <t> :: reference Compile Error </t>

时间:2012-03-02 12:59:19

标签: c++ visual-studio list stl

我正在将项目从Visual Studio 6转换为Visual Studio 2010.该项目大量使用STL。有一个自定义类,它为子类列表添加更多方法。以下是我得到的代码和编译器错误。

    #include <list> 
    namespace mySpace 
    { 
    template <class T> 
    class MyList : public std::list<T> 
    { 
        ...
    };

    template <class T>
    MyList<T>::reference MyList<T>::find(const_reference p_constreferenceItem) const
    {
     return std::find(this->begin(), this->end(), p_constreferenceItem);
    }
   } // namespace mySpace

错误:

Error   2   error C2143: syntax error : missing ';' before 'MySpace::MyList<T>::find'   c:\myproject\mylist.h   300 1
Error   3   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   c:\myproject\mylist.h   300 1   
Error   4   error C2888: 'MyList<T>::reference reference' : symbol cannot be defined within namespace 'MySpace' c:\myproject\mylist.h   300 1

任何想法导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

好像你只是在typename前面缺少一个MyList<T>::reference,因为它是一个依赖类型(一个取决于T的类型)并且编译器没有'知道MyList<T>::reference是一种类型,默认情况下它假定它是一个变量名:

template <class T>
typename MyList<T>::reference MyList<T>::find(
                              const_reference p_constreferenceItem) const

const_reference你不需要这个,因为编译器只要看到MyList<T>(方法名称)的::范围,就会在const_reference范围内。现在知道typename命名一个类型。同样,当您已经在MyList<T>的范围内时,您不需要使用{{1}},例如在类定义中声明或内联定义方法时。

我不确定为什么VC6允许这样做。但是我们都知道VC6和模板不是那么大的朋友,更不用说当时C ++模板的松散规范及其行为。

免责声明:如果此处使用的术语有点非正式,请对语言律师表示不满。