假设我有一个基于模板 ThingType
的类。在 header 中,我使用它来 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;
}
关于c++ - 如何从模板化类方法返回依赖类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436715/