c++ - 一对一协会

标签 c++ oop data-structures

在 C++ 中表示一对一对象关联的最佳方式是什么?它应该尽可能自动和透明,这意味着当设置或重置一端时,另一端将被更新。可能一个类似于指针的接口(interface)是理想的:

template<typename AssociatedType>
class OneToOne{
    void Associate(AssociatedType &);
    AssociatedType &operator* ();
    AssociatedType *operator->();
} 

有没有更好的方法或者有没有完整的实现?

编辑:

期望的行为:

struct A{
    void Associate(struct B &);
    B &GetAssociated();
};

struct B{
    void Associate(A &);
    A &GetAssociated();
};

A a, a2;
B b;

a.Associate(b);
// now b.GetAssociated() should return reference to a

b.Associate(a2);
// now b.GetAssociated() should return reference to a2 and 
// a2.GetAssociated() should return reference to b
// a.GetAssociated() should signal an error

最佳答案

未经测试,但你可以使用一个简单的装饰器

template <typename A1, typename A2>
class Association
{
public:
  void associate(A2& ref)
  {
    if (_ref && &(*_ref) == &ref) return; // no need to do anything
    // update the references
    if (_ref) _ref->reset_association();
    // save this side
    _ref = ref;
    ref.associate(static_cast<A1&>(*this));
  }

  void reset_association() { _ref = boost::none_t(); }

  boost::optional<A2&> get_association() { return _ref; }

private:
  boost::optional<A2&> _ref;
};

现在:

struct B;

struct A : public Association<A, B> {
};

struct B : public Association<B, A> {
};

现在应该正确处理这些操作。

A a, a2;
B b;

a.associate(b);
b.associate(a2);

注意:我使用 boost::optional 来保存引用而不是指针,没有什么可以阻止您直接使用指针。我认为 C++ 中默认不存在你所追求的构造,这就是为什么你需要类似上面的东西才能让它工作......

关于c++ - 一对一协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4584518/

相关文章:

java - 我应该如何填充我的对象?

php - 在 PHP 中,如何在没有条件语句的情况下选择 3 个子类中的 1 个

c++ - 为什么编译器认为我的对象声明是函数声明?

c++ - 使用 tcp::acceptor::async_accept 的套接字指针所有权转移

oop - 为什么维基百科说 "Polymorphism is not the same as method overloading or method overriding."

data-structures - 如何检查图形是否不是树?

python - 合并嵌套的 defaultdict

data-structures - 爬山和单对最短路径算法

c++ - 为什么我的 char* 无故改变?

c++ - 在 C++ 中将整数转换为固定长度的字符数组