![](/img/trans.png)
[英]How to return std::string from method of templated class, no matter the type?
[英]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.