如何使用元组修复多个关联关系?

时间:2015-08-20 09:41:22

标签: c++ types associations

我制作了一个简单的系统来处理关联(我做了一对一的关联和一对多的关联,但我会专注于这里的一对一案例)。如果一个对象只有一种类型的关联,我需要处理几种类型的关联(即,类型A的对象a0与类型B的对象b0和类型的另一个对象c0相关联,它正如我所希望的那样工作。 C)。 我尝试通过将关联类封装在元组中来实现(如果有更好/更简单的方法来执行此操作,请告诉我)但我现在遇到类型问题。这是我当前的代码(现在没有使用某些模板,比如ind1,但我可能会在以后需要它):

template <typename A1, typename A2, size_t ind1, size_t ind2>
class Association
{
public:
    virtual ~Association()
    {
        if (!this->empty())
        {
            this->clear_associations();
        }
    }

    void associate(A2* ref)
    {
        if (!this->empty() && _ref == ref)
        {
            return;
        }

        if (_ref)
        {
            std::get<ind2>(*_ref).reset_association();
        }

        _ref = ref;
        std::get<ind2>(*ref).associate(static_cast<A1*>(this));
    };

    void associate(A2& ref)
    {
        this->associate(&ref);
    };

    bool empty() const
    {
        if (!_ref)
            return true;
        else
            return false;
    }

    void remove_association(A2* ref)
    {
        if (_ref == ref)
        {
            this->reset_association();
            std::get<ind2>(ref)->remove_association(static_cast<A1*>(this));
        }
    }

    void remove_association(A2& ref)
    {
        this->remove_association(&ref);
    }

    void reset_association()
    {
        _ref = 0;
    }

    void clear_associations()
    {
        if (_ref)
        {
            std::get<ind2>(_ref)->remove_association(static_cast<A1*>(this));
        }
        this->reset_association();
    }

    A2* get_association() const
    {
        return _ref;
    }

private:
    A2* _ref=0;
};

template <typename... T>
class Relations : public std::tuple<T...>
{
public:
    Relations();
    virtual ~Relations();
};

class J;
class K;

class I : public Relations<Association<I, J, 0, 0>, Association<I, K, 1, 0>>
{
public:
    std::string type="I";
};

class J : public Relations<Association<J, I, 0, 0>>
{
public:
    std::string type="J";
};

class K : public Relations<Association<K, I, 0, 1>>
{
public:
    std::string type="K";
};

int main()
{
    I i;
    J j;
    K k;
    std::get<0>(i).associate(j);

    return 0;
}

这里的问题是当我尝试做std :: get(* ref).associate(static_cast(this)); A1是I型,而它是Association类型,由于元组不能直接铸造。有什么好办法呢?

1 个答案:

答案 0 :(得分:1)

您可以为Relation创建自己的获取:

namespace std
{
    template <std::size_t I, typename... Ts>
    auto get(Relations<Ts...>& r)
    -> typename std::tuple_element<I, std::tuple<Ts...>>::type&
    {
        return static_cast<typename std::tuple_element<I, std::tuple<Ts...>>::type&>(r);
    }
}

Live Demo