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

标签 c++ class templates typedef

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

相关文章:

c++ - 如何将 std::function 分配给 C++ 中的运算符?

swift - 知道变量是类还是结构的实例

c++ - 如何从 Int2Type 构建 Type2Int?

基类型的 C++ 模板继承问题

c++ - 使用基于 IOCP 的客户端的每个 IO 数据

c++ - seekg 是如何找到文件末尾的?

c++ - 复杂的 if 条件

javascript - javascript函数可以应用于某个CSS类的所有元素吗?

swift - 检查对象是否是 Swift 中类元类型的实例

c++ - 帮助模板化字节交换功能,性能受到影响?