vendredi 21 août 2015

Use a union as a item-type in a tree in order to store two different data types

Please consider the following code:

union tree_item
{
    tree_item(std::valarray<double> const& point)
        : point(point)
    { }
    tree_item(unsigned coord, double coord_value)
        : splitting_line({ coord, coord_value })
    { }

    struct {
        unsigned coord;
        double coord_value;
    } splitting_line;
    std::valarray<double> point;
};

How can we make sure, that if a tree_item object stores a point, the destructor of point is called? I could write

~tree_item() {
    point.~valarray();
}

but I assume, that this leads to undefined behavior, if we had assigned values to coord or coord_value.

All I want to do, is to use tree_item for T in

template<typename T>
struct tree_node
{
    tree_node(T const& item)
        : item(item)
    { }
    tree_node(T&& item)
        : item(std::move(item))
    { }

    bool is_leaf() const noexcept {
        return !left && !right;
    }

    T item;
    std::shared_ptr<tree_node<T>> left, right;
};

splitting_line and point are the two types of items, that I want to store in the tree. Clearly, I could write a base class and derived classes for splitting_line and point, respectively. However, since in this case there is no kind of operation that I want to perform on these items (I just want to store these different types) and I would need to use dynamic_cast or some kind of type-flag, this would make my code much too complicated.

So, what should I do?

Aucun commentaire:

Enregistrer un commentaire