typedef typename和Dependent范围

时间:2013-12-12 20:36:11

标签: c++ templates typedef

这个问题与以下内容有关: Dependent scope and nested templatesWhy do I need to use typedef typename in g++ but not VS?Nested templates with dependent scope

根据这个答案https://stackoverflow.com/a/3311640/1559666我应该将typename添加到typedef。

问题是 - 为什么我会收到错误?

#include <iostream>

#include <vector>
#include <iterator>


template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class PtrVector
{
private:
    typedef std::vector<_Tp, _Alloc> VectrorT;
    typedef typename std::vector<_Tp, _Alloc> VT;

public:

    typename std::vector<_Tp, _Alloc>::const_iterator test(){}
    VT::const_iterator test2(){}    // why there is an error here?

};


int main() {
    return 0;
}

http://ideone.com/ghUQ2b

1 个答案:

答案 0 :(得分:1)

您的Ideone示例fixed

#include <iostream>

#include <vector>
#include <iterator>


template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class PtrVector
{
private:
    typedef std::vector<_Tp, _Alloc> VectrorT;
    typedef typename std::vector<_Tp, _Alloc>::const_iterator VTConstIter;
 //         ^^^^^^^^                         ^^^^^^^^^^^^^^^^

public:

    typename std::vector<_Tp, _Alloc>::const_iterator test(){}
 // ^^^^^^^^                         ^^^^^^^^^^^^^^^^
    VTConstIter test2(){}

};


int main() {
    return 0;
}

至于您的评论,请参阅以下variants

// ...
typedef typename VectrorT::const_iterator VTConstIter; // also works
// ...
typename VectrorT::const_iterator test(){} // also works
// ...

我希望能够进一步澄清编译器内容的进一步发展。