如何从模板化的类方法返回依赖类型

How can I return a dependent type from templated class method?

本文关键字:类方法 返回 依赖 类型      更新时间:2023-10-16

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

刚刚发现了这个问题的另一个答案,它不涉及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,这可能会很有用。