2015-04-03 81 views
3

比方說,我有一個基於模板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; 
} 

回答

7
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; 
} 
+0

真的很酷。謝謝! – 2015-04-03 17:30:05

2

跨越另一個答案剛來到這個問題,不涉及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困住,可能會很有用。