2010-08-10 95 views
1

我希望能夠創建一個函數,在該函數中指定一個參數以同時爲該容器提供模板化容器和模板化元素類型。這可能嗎?我收到「錯誤C2988:不可模仿的模板聲明/定義」等等。這是有問題的功能。C++模板 - 指定容器類型和它容納的容器元素類型

template<class Iter, class Elem> 
void readIntoP(Iter<Elem> aCont){ 
ifstream ifss("data.dat"); 
string aString; 
int counter = 0; 
item tempItem; 
while(ifss >> aString){ 
    istringstream iss(aString); 
    if(counter == 0){ 
     tempItem.name = aString; 
    }else if(counter == 1){ 
     int aNum = 0; 
     iss >> aNum; 
     tempItem.iid = aNum; 
    }else{ 
     double aNum = 0; 
     iss >> aNum; 
     tempItem.value = aNum; 
     aCont.push_back(tempItem); 
     counter = -1; 
    } 
    ++counter; 
    } 
} 
+0

重複排序-的[C++函數模板編譯錯誤「‘containerType’不是一個模板」 ](http://stackoverflow.com/questions/3436518/c-function-template-compiles-error-containertype-is-not-a-template)(解決方案至少是完全相同的)。 – 2010-08-11 00:03:03

回答

4

您將需要使用模板模板參數,例如,

template <template <class> class Iter, class Elem> 
void readIntoP(Iter<Elem> aCont) { /* ... */ } 

但是請注意,該標準庫中的容器採取多種模板參數(vector,例如,有兩個:一個是要存儲的值類型和分配器要使用的值類型)。

您可能會改用一個模板參數的實例化的容器類型,然後使用它的value_type的typedef:

template <typename ContainerT> 
void readIntoP(ContainerT aCont) 
{ 
    typedef typename ContainerT::value_type ElementT; 
    // use ContainerT and ElementT 
} 
+0

參數化迭代器通常比容器更好。 (這是OP在做什麼。) – Potatoswatter 2010-08-11 02:44:22

+0

@Patatoswatter:很難說。問題標題和變量名稱意味着OP正試圖傳遞一個容器; typename意味着OP正在嘗試傳遞某種類型的迭代器。無論哪種方式,迭代器也有'value_type' typedef。我同意通常最好傳遞迭代器而不是容器,但通常傳遞整個容器是有用的。 – 2010-08-11 02:50:56

+0

我聽說標準沒有指定容器有多少個參數。一個向量至少有兩個,但實現可能會爲了他們自己的目的增加更多,使得「模板模板」的可移植性降低了? – UncleBens 2010-08-11 06:55:34