如何編寫在任意類型的任意容器上運行的模板函數?比如我怎麼概括這個虛擬函數模板模板C++函數
template <typename Element>
void print_size(const std::vector<Element> & a)
{
cout << a.size() << endl;
}
到
template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
cout << a.size() << endl;
}
這裏是一個典型的使用
std::vector<std::string> f;
print_size(f)
這給錯誤
tests/t_distances.cpp:110:12: error: no matching function for call to ‘print(std::vector<std::basic_string<char> >&)’. I'm guessing I must tell the compiler something more specific about what types that are allowed.
這是什麼調用模板的變種,我該如何解決?
如果您需要獲取「包含」類型,該怎麼辦?就像如果你想創建一個函數,它可以從兩個std :: vector(一個用於鍵,另一個用於值)爲你提供一個std :: map。但是你可以像使用begin()和end()迭代器的自定義類一樣使用std :: vector之外的其他東西。 – ibizaman
@ibizaman這就是typendefs的用途。只需使用'typename Container :: value_type'(注意前綴'typename',這很重要;還有其他問題解釋了原因)。 –
是這個value_type標準嗎?那麼,我知道它是stl :: vector中的stl,但它是自定義類的公認方法嗎? – ibizaman