本文介绍了为什么在这个模板中使用typedef是必要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 当我在Visual Studio 2005中编译此代码时:When I compile this code in Visual Studio 2005: template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ) { iter = begin(); }我得到这些错误:c:\home\code\scantest\stltest1\stltest1.cpp(33) : error C2244: 'CFooVector<T>::SetToFirst' : unable to match function definition to an existing declaration c:\home\code\scantest\stltest1\stltest1.cpp(26) : see declaration of 'CFooVector<T>::SetToFirst' definition 'void CFooVector<T>::SetToFirst(std::vector<CFoo<T>>::iterator &)' existing declarations 'void CFooVector<T>::SetToFirst(std::_Vector_iterator<_Ty,_Alloc::rebind<_Ty>::other> &)' $ b b 如果我添加一个typedef到CFooVector模板,我可以得到代码编译和工作:If I add a typedef to the CFooVector template, I can get the code to compile and work: template <class T> class CFooVector : public std::vector<CFoo<T>> { public: typedef typename std::vector<CFoo<T>>::iterator FooVIter; void SetToFirst( FooVIter & iter ); }; template <class T> void CFooVector<T>::SetToFirst( FooVIter & iter ) { iter = begin(); }我的问题是,为什么typedef在使用裸'typename std :: vector> :: iterator'声明无效?My question is, why does the typedef work when using the bare 'typename std::vector>::iterator' declaration did not work?推荐答案这也编译好,并揭示了VC ++混淆 - 分配器类型的来源。显然在类VS之外选择不同的默认值。This compiles as well and reveals the source of VC++ confusion -- allocator type. Apparently outside of the class VS selects different default. Or maybe it can't recognize them to be the same.在VS2008上(按原样)和VS2003(在>之间有空格)进行编译Compiles on VS2008 (as is) and VS2003 (with space between >>)template <class T>class CFoo{public: T m_t;};template <class T>class CFooVector : public std::vector<CFoo<T>>{public: void SetToFirst(typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter);};template <class T>void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter ){ iter = begin();} GCC 3.4想要this-> begin()和space,编译代码没有显式的分配器类型...肯定看起来像MS编译器不那么聪明,因为它应该是...GCC 3.4 wanted this->begin() and space, but otherwise it can compile the code without explicit allocator type... Definitely looks like MS compiler not as smart as it should be... 这篇关于为什么在这个模板中使用typedef是必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-31 02:43