[英]How can I return a dependent type from templated class method?
Let's say I have a class based on a template ThingType
. 假设我有一个基于模板
ThingType
。 In the header, I use this to typedef
a dependent type VectorThingType
. 在报头中,我使用它来
typedef
一个依赖型VectorThingType
。 I'd like to return this from a method GetVectorOfThings()
. 我想从方法
GetVectorOfThings()
返回这个。 If I set VectorThingType
as the return type, I get a Does not name a type
error, as the type wasn't defined in this scope. 如果我将
VectorThingType
设置为返回类型,我会得到一个Does not name a type
错误,因为该范围中未定义类型。 Is there any way to do this without duplicating the code in the typedef
? 有没有办法在不重复
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;
}
Just came across another answer to this question, which doesn't involve c++11. 刚刚遇到了这个问题的另一个答案,它不涉及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;
}
Basically involves assuring the compiler that you are, in fact, dealing with a type via typename
and then properly scoping the type using Thing< ThingType >::
. 基本上涉及向编译器确保您实际上是通过
typename
处理类型,然后使用Thing< ThingType >::
正确地确定类型。 Could be useful if you are stuck with c++03 for some reason. 如果由于某种原因你被c ++ 03困住可能会有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.