构建本身是 shared_ptr 类型的模板化容器 [英] constructing templated containers that are themselves shared_ptr types

查看:93
本文介绍了构建本身是 shared_ptr 类型的模板化容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在思考这个问题时遇到了一些困难,可能是因为我不完全了解底层机制.

I'm having some difficulty wrapping my head around this one, likely because I don't fully understand the underlying mechanics.

我有一个如下所示的结构:

I have a struct like the following:

template <class T>
struct A {
    int id;
    T x;
}

这个结构体被用作 shared_ptr 的类型:

This struct is then used as a type for a shared_ptr:

typedef std::shared_ptr<A> A_ptr;

依次存储在地图中:

typedef unordered_map<int , A_ptr> AMap;

但是,当我编译时,出现以下错误:

However, when I compile, I get the following error:

> error: type/value mismatch at argument 1 in template parameter list
> for 'template<class _Tp> class std::shared_ptr'   typedef
> std::shared_ptr<A> A_ptr;

我已经阅读了关于类似问题的其他帖子,但他们都建议在结构内创建 shared_ptr A.我已经尝试过这个,即使我无法从逻辑上理解为什么它会帮助我解决问题,但它不起作用.任何帮助表示赞赏.

I have read other posts about a similar issue, but all of them recommend creating the shared_ptr A inside the struct. I've tried this, even though I can't logically understand why it would help with my problem, but it doesn't work. Any help is appreciated.

推荐答案

A 是模板的名称,而不是类的名称.如果你要命名一个专业,你的 typedef 就可以了:

A is the name of a template, not the name of a class. If you were to name a specialization, your typedef would be fine:

typedef std::shared_ptr<A<int>> A_int_ptr; // A<int> **is** a class

如果您想保持代码通用,您需要切换到使用别名模板而不是常规类型别名:

If you want to keep the code generic, you'll need to switch to using alias templates instead of regular type aliases:

template<typename T>
using A_ptr = std::shared_ptr<A<T>>;

template<typename T>
using AMap = std::unordered_map<int , A_ptr<T>>;

现在一切都已正确模板化,实例化取决于您打算传递给 A 的类型 T.

Now everything is properly templated, and the instantiations depend on the type T you intend to pass onto A.

这篇关于构建本身是 shared_ptr 类型的模板化容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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