[英]Template definition with template template parameter for class that can specialize, for instance, to std::vector<std::string> or std::map<std::tree>
我想創建一個模板類,它可以容納容器和容器的任何組合。 例如, std::vector<std::string>
或std::map<std::tree>
。
我嘗試了很多組合,但我必須承認模板的復雜性讓我感到壓力。 我編譯的關閉是這樣的:
template <class Vector, template <typename, class Containee = std::string> class Container>
class GenericContainer
{
Container<Containee> mLemario;
};
雖然它編譯到目前為止,然后,當我想實例化它時,我遇到了很多錯誤。
MyContainer<std::vector, std::string> myContainer;
我是否使用正確的方法來創建這種類?
對於std::vector
(等)@ songyuanyao提供了一個很好的答案。 但既然你也提到過std::map
,我會在網上添加一個@ songyuanyao答案的簡單擴展。
#include <iostream>
#include <vector>
#include <string>
#include <map>
template <template <typename...> class Container, typename Containee = std::string, typename... extras>
class GenericContainer
{
Container<Containee, extras ...> mLemario;
// Use 'Containee' here (if needed) like sizeof(Containee)
// or have another member variable like: Containee& my_ref.
};
int main()
{
GenericContainer<std::vector, std::string> myContainer1;
GenericContainer<std::vector, std::string, std::allocator<std::string>> myContainer2; // Explicitly using std::allocator<std::string>
GenericContainer<std::map, std::string, int> myContainer3; // Map: Key = std::string, Value = int
}
我想創建一個模板類,它可以容納容器和容器的任何組合
您應該使用參數包作為模板模板參數Container
和Containee
,然后它們可以與任意數量/類型的模板參數一起使用。 例如
template <template <typename...> class Container, typename... Containee>
class GenericContainer
{
Container<Containee...> mLemario;
};
然后
GenericContainer<std::vector, std::string> myContainer1;
GenericContainer<std::map, std::string, int> myContainer2;
標准容器為其元素類型聲明名稱,因此您可以編寫
template<typename Container>
class GenericContainer
{
using Containee = typename Container::value_type;
};
你可以像這樣使用它:
int main()
{
GenericContainer<std::vector<std::string>> myContainer;
}
您可以將非默認分配器與此類容器一起使用,但不能輕松創建具有不同元素類型的類似容器。 這可能是也可能不是你的障礙。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.