假设我有一个基于模板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;
}

最佳答案

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;
}

07-27 13:51