考虑以下从我编写的迭代器中简化的代码:
#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
我需要写出一切。为什么呢?
如果我将v
中WithTemplate
的声明替换为注释的声明,则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)