Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 构建自身为共享类型的模板化容器_C++_Templates_Shared Ptr - Fatal编程技术网

C++ 构建自身为共享类型的模板化容器

C++ 构建自身为共享类型的模板化容器,c++,templates,shared-ptr,C++,Templates,Shared Ptr,我在这件事上有点困难,可能是因为我不完全理解其背后的机制 我有一个如下所示的结构: template <class T> struct A { int id; T x; } 模板 结构A{ int-id; tx; } 然后将此结构用作共享ptr的类型: typedef std::shared_ptr<A> A_ptr; typedef std::shared_ptr A_ptr; 然后存储在地图中: typedef unordered_map<

我在这件事上有点困难,可能是因为我不完全理解其背后的机制

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

template <class T>
struct A {
    int id;
    T x;
}
模板
结构A{
int-id;
tx;
}
然后将此结构用作共享ptr的类型:

typedef std::shared_ptr<A> A_ptr;
typedef std::shared_ptr A_ptr;
然后存储在地图中:

typedef unordered_map<int , A_ptr> AMap;
typedef无序映射AMap;
但是,当我编译时,会出现以下错误:

> 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;
>错误:模板参数列表中参数1的类型/值不匹配
>对于“模板类std::shared_ptr”类型定义
>std::共享\u ptr A \u ptr;

我读过关于类似问题的其他帖子,但所有帖子都建议在结构内部创建共享_ptr a。我尝试过这个方法,尽管我无法从逻辑上理解为什么它能帮助解决我的问题,但它不起作用。非常感谢您的帮助。

A
是模板的名称,而不是类的名称。如果您要命名一个专门化,您的
typedef
就可以了:

typedef std::shared_ptr<A<int>> A_int_ptr; // A<int> **is** a class
typedef std::shared_ptr A_int_ptr;//一个**就是一个班级
如果要保持代码的通用性,则需要切换到使用别名模板而不是常规类型别名:

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

template<typename T>
using AMap = std::unordered_map<int , A_ptr<T>>;
模板
使用A_ptr=std::shared_ptr;
样板
使用AMap=std::无序的_映射;

现在,所有内容都已正确模板化,实例化取决于要传递到
A
的类型
T

struct A
缺少分号。您没有struct
A
。您有一个结构模板
a