加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 指向模板类的指针作为该类参数

发布时间:2020-12-16 09:40:37 所属栏目:百科 来源:网络整理
导读:基本上在尝试通过邻接列表实现图形时,我很难定义图形节点: template typename Vertex,typename Edge,typename EdgeLink = std::pair Edge,GraphNode* ,typename Alloc = std::allocator EdgeLink class GraphNode{public: Vertex vertex; std::list EdgeLin
基本上在尝试通过邻接列表实现图形时,我很难定义图形节点:

template <
    typename Vertex,typename Edge,typename EdgeLink = std::pair< Edge,GraphNode* >,typename Alloc = std::allocator< EdgeLink >
>
class GraphNode
{
public:
    Vertex vertex;
    std::list< EdgeLink,Alloc > neighbours;
};

我意识到我不能给GraphNode模板指针赋予参数,因为它们还没有定义.我对c模板大师的问题是:在这种情况下使用了什么技术?

谢谢.

解决方法

精确分配器并不需要精确分配器可以用于什么.例如,在std :: list< T>中传递的分配器是std :: allocator< T>但是列表将分配_ListNode< T> (实施定义).这是因为分配器需要提供 rebind机制.

template <
    typename Vertex,typename Allocator = std::allocator<void*>
>
class GraphNode
{
public:
    typedef GraphNode<Vertex,Edge,Allocator> NodeType;
    typedef std::pair< Edge,NodeType* > LinkType;
    typedef typename Allocator::template rebind<LinkType>::other AllocatorType;

    Vertex vertex;
    std::list< LinkType,AllocatorType > neighbours;
};

在ideone行动.

请注意,即使list本身会重新绑定,您仍然应该这样做,因为分配器类型引用和指针(及其const版本)将作为typedef在列表中拉出.

编辑:允许容器规范.

这很棘手,因为遗憾的是,只有在GraphNode中才定义分配器,因此您只需要在类中传递给容器,因此不能在模板外部使用它.

这意味着使用模板模板参数,因此我们需要“修复”arity.由于向量和列表只有两个参数,我们很幸运,但它可能并不总是保持…幸运的是,C 11允许模板别名,对用户来说不会太苛刻.

template <
    typename Vertex,template <typename,typename> class Container = std::vector,Container,NodeType* > LinkType;
    typedef typename Allocator::template rebind<LinkType>::other AllocatorType;
    typedef Container<LinkType,AllocatorType> NeighboursType;

    Vertex vertex;
    NeighboursType neighbours;
};

这可以调用:

GraphNode<std::string,int>
GraphNode<std::string,int,std::list>
GraphNode<std::string,std::vector>

Demo.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读