具有模板模板参数的模板定义可以专用于例如 std::vector&lt;std::string&gt;或 std::map<std::tree> [英] Template definition with template template parameter for class that can specialize, for instance, to std::vector&lt;std::string&gt; or std::map&lt;std::tree&gt;

查看:32
本文介绍了具有模板模板参数的模板定义可以专用于例如 std::vector&lt;std::string&gt;或 std::map<std::tree>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个模板类,可以容纳容器和容器的任意组合.例如,std::vectorstd::map,例如.

I want to create a template class that can hold any combination of container and containee. For example, a std::vector<std::string> or std::map<std::tree>, for instance.

我尝试了很多组合,但我必须承认模板的复杂性让我不知所措.我编译的关闭是这样的:

I have tried a lot of combinations, but I must admit that the complexity of templates overwhelms me. The closes I have made compile is something like this:

template <class Vector, template <typename, class Containee = std::string> class Container>
class GenericContainer
{
    Container<Containee> mLemario;
};

尽管到目前为止它可以编译,但是当我想实例化它时,我会收到很多错误.

Although it compiles so far, then, when I want to instantiate it I rreceive lots of errors.

MyContainer<std::vector, std::string> myContainer;

我是否使用了正确的方法来创建这种类?

Am I using the correct approach to create that kind of class?

推荐答案

对于 std::vector(等)@songyuanyao 提供了很好的答案.不过既然你也提到了std::map,那我就加个@songyuanyao 的回答,在线.

For std::vector (and the like) @songyuanyao provided an excellent answer. But since you also mentioned std::map, I'll add a simple extension of @songyuanyao's answer, online.

#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
}

这篇关于具有模板模板参数的模板定义可以专用于例如 std::vector&lt;std::string&gt;或 std::map<std::tree>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆