繁体   English   中英

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

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

假设我有一个基于模板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困住可能会有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM