我在教C++自己的模板編程,所以我的一些假設可能是錯誤的 - 請糾正我,如果你看到任何錯誤。專門設計一個包含模板模板的模板
我想使用STL列表作爲函數的模板參數。該函數應該用於各種數據類型,所以我在其原始聲明中將函數定義爲template<class T>
而不是template<template<> class T>
。我現在想專門支持模板類。
template<class T>
void function(T param)
{
// do something with T
}
template<template <class T, class Allocator> class listPlaceholder>
void function(std::list<T, Allocator> param)
{
// do something with every element in param (I actually need to know it's a list)
std::list<T, Allocator>::iterator current = param.begin();
std::list<T, Allocator>::iterator end = param.end();
do {
function<T>(*current);
} while (++current != end);
}
的問題是,當我嘗試編譯此代碼(GCC下),它說,T
和Allocator
未在範圍內定義。我的主要問題是「我如何專注於模板類?」其次,如果可能的話,「我如何提取模板模板參數?」。
如前所述,我正在學習模板編程,因此歡迎使用明顯的解決方案。
我使用'listPlaceholder'和'std :: list'爲了專門爲'std :: list's,同時保持其他兩個參數模板類的任何特化打開(例如我也使用'std :: pair') 。正如我向其他評論者提及的那樣,額外的模板參數是否意味着您不能在原始函數中使用此修改後的功能。 – fuseinabowl
@fuseinabowl,啊我明白了。那麼,因爲你沒有專精,所以你不需要爲任何更專業化而「保持開放」。無論如何,您無法爲參數化的'std :: list '專門化一個函數模板,因爲這需要部分特化,而功能模板則無法完成。你可以在裏面粘貼'std :: list',稍後爲其他類型添加更多的重載。編譯器將在一次調用中選擇最專業的模板(即最接近參數的模板)。 –
我嘗試了第一個 - 我不知道如何編寫代碼。你能給我一個模板函數聲明的代碼示例嗎? – fuseinabowl