Hol*_*ndo 6 c++ templates stl vector
我想创建一个模板类,它可以容纳容器和容器的任何组合.例如,a std::vector<std::string>或者std::map<std::tree>,例如.
我尝试了很多组合,但我必须承认模板的复杂性让我感到压力.我编译的关闭是这样的:
template <class Vector, template <typename, class Containee = std::string> class Container>
class GenericContainer
{
Container<Containee> mLemario;
};
Run Code Online (Sandbox Code Playgroud)
虽然它编译到目前为止,然后,当我想实例化它时,我遇到了很多错误.
MyContainer<std::vector, std::string> myContainer;
Run Code Online (Sandbox Code Playgroud)
我是否使用正确的方法来创建这种类?
对于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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |