sud*_*all 5 c++ templates typedef class
假设我有一个基于模板的类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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)