2015-04-03 71 views
3

比方说,我有一个基于模板ThingType的课程。在标题中,我用这个typedef一个依赖类型VectorThingType。我想从方法GetVectorOfThings()中返回。如果我将VectorThingType设置为返回类型,则会出现Does not name a type错误,因为该类型未在此范围内定义。有没有办法在不重复typedef中的代码的情况下做到这一点?如何从模板类方法返回依赖类型?

#include <vector> 
#include <iostream> 

template< typename ThingType > 
class Thing 
{ 
public: 

ThingType aThing; 
typedef std::vector<ThingType> VectorThingType; 
VectorThingType GetVectorOfThings(); 

Thing(){}; 
~Thing(){}; 

}; 

template< typename ThingType > 
//VectorThingType // Does not name a type 
std::vector<ThingType> // Duplication of code from typedef 
Thing<ThingType> 
::GetVectorOfThings() { 
    VectorThingType v; 
    v.push_back(this->aThing); 
    v.push_back(this->aThing); 
    return v; 
} 

回答

7
template< typename ThingType > 
auto // <-- defer description of type until... 
Thing<ThingType> 
::GetVectorOfThings() 
-> VectorThingType // <-- we are now in the context of Thing<ThingType> 
{ 
    VectorThingType v; 
    v.push_back(this->aThing); 
    v.push_back(this->aThing); 
    return v; 
} 
+0

真的很酷。谢谢! – 2015-04-03 17:30:05

2

跨越另一个答案刚来到这个问题,不涉及C++ 11。

template< typename ThingType > 
typename Thing<ThingType>::VectorThingType 
Thing<ThingType> 
::GetVectorOfThings() 
{ 
    VectorThingType v; 
    v.push_back(this->aThing); 
    v.push_back(this->aThing); 
    return v; 
} 

主要涉及确保你是编译器,实际上,通过typename与类型处理,然后正确使用范围界定的Thing<ThingType>::类型。如果你出于某种原因被C++ 03困住,可能会很有用。