如何从模板化的类方法返回依赖类型
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,这可能会很有用。
相关文章:
- 从父类方法返回子类对象
- 我的模板类方法返回错误类型?
- 我无法使用C++指针指向类方法返回的 std::vector
- 类方法返回指向具有模板的类成员的指针
- 从类方法返回 "const char*" 作为 std::string&
- 从基类方法返回对派生类的引用
- 如何打印通过类方法返回的值
- 如何检查模板类方法返回类型
- 如何<double>从基于 QObject 的类方法返回 QList 以在 Qt 脚本中使用
- 类方法返回最后由C 组成的
- 如何从模板化的类方法返回依赖类型
- 为什么有些类方法返回"*this"(self的对象引用)?
- C++类方法返回不同的类型
- 基类方法返回派生类 objec
- 从类方法返回结构
- 从类方法返回作用域枚举时,命名空间混淆
- Turtle Mock: MOCK_EXPECT如果被Mock的类方法返回值则失败
- 简单的一行类方法返回错误的值
- 从类方法返回成员unique_ptr
- c++从类方法返回一个对象数组