仅当类不是模板时,为什么超类typedef在范围内?

时间:2014-08-29 21:29:05

标签: c++ templates name-lookup

考虑以下从我编写的迭代器中简化的代码:

#include <iterator>
#include <iostream>
#include <typeinfo>
#include <array>

struct NoTemplate:public std::iterator<std::forward_iterator_tag, 
                                       std::array<int, 5> >{
    static value_type v;
};

template<int n>
struct WithTemplate:public std::iterator<std::forward_iterator_tag, 
                                         std::array<int, n> >{
    //static value_type v;  //Doesn't work
    static typename std::iterator<std::forward_iterator_tag, std::array<int, n> >::value_type v;
};

int main(){
    std::cout << "NoT:" << typeid(NoTemplate::v).name() << "\nWT:" 
              << typeid(WithTemplate<5>::v).name() << "\n";
    return 0;
}

NoTemplate中,我可以轻松访问std::iterator<std::forward_iterator_tag, array<int, 5> >::value_type value_type。但是,在WithTemplate我需要写出一切。为什么呢?

如果我将vWithTemplate的声明替换为注释的声明,则g ++ 4.8.1会出错:

foo.cpp:14:12: error: ‘value_type’ does not name a type
     static value_type v;  //Doesn't work
            ^
foo.cpp:14:12: note: (perhaps ‘typename std::iterator<std::forward_iterator_tag, std::array<int, n> >::value_type’ was intended)

0 个答案:

没有答案