在std :: vector声明中使用void pointer有多糟糕? [英] How bad is to use void pointer in std::vector declaration?

查看:186
本文介绍了在std :: vector声明中使用void pointer有多糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的类,如下所示:

I have two different classes as below:

class text
{ };

class element
{ };

我想将它们存储在类节点

template <typename T>
class node
{
    T cargo;

    std::vector<void*> children;

    node(T cargo) : cargo(cargo)
    { };

    void add_child(T node)
    {
        this->children.push_back((void*) node);
    }
}



因此我将以这种方式调用节点, text 元素的:

element div;
text msg;

node<element> wrapper(div);

wrapper.add_child(msg);

EDIT :要取回我使用的内容 T typedef type; 并将void指针转换为(type *)

EDIT: To get back the content I use T typedef type; and convert void pointer to (type*).

我知道这不是很优雅也不实用,但我只是不知道什么是正确的做法。

I know that's not very elegant nor functional, but I just can't figure out what's the correct way of doing that. So please tell me if this is practically acceptable and if it is not, how to do that in the proper manner.

提前感谢!

推荐答案

#include <vector>
using namespace std;

class Element {};
class Text {};
class Nothing {};

class Node
{
private:
    vector< Node* >     children_;
protected:
    Node() {}
public:
    void add( Node* p ) { children_.push_back( p ); }
    virtual ~Node() {}
};

template< class Cargo >
class CargoNode
    : public Node
{
private:
    Cargo   cargo_;
public:
    CargoNode(): cargo_() {}
};

typedef CargoNode< Element >    ElementNode;
typedef CargoNode< Text >       TextNode;
typedef CargoNode< Nothing >    RootNode;

int main()
{
    RootNode*   root    = new RootNode;

    root->add( new ElementNode );
    root->add( new ElementNode );
    root->add( new TextNode );
    root->add( new ElementNode );   
    // Etc.
}



<

Cheers & hth.,

PS:错误检查,生命周期管理,迭代等在此示例代码中省略。

PS: Error checking, lifetime management, iteration etc. omitted in this example code.

这篇关于在std :: vector声明中使用void pointer有多糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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