如何使用元组修复多个关联关系
How to fix multiple association relashionships using a tuple?
我做了一个简单的系统来处理关联(我做了一对一关联和一对多关联,但这里我将重点关注一对一的情况)。它是工作,因为我希望,如果一个对象只有一种类型的关联,但我需要处理几种类型的关联(即。A类型的对象a0与B类型的对象b0和C类型的对象c0相关联)。我试图通过将关联类封装在元组中来做到这一点(如果有更好/更简单的方法来做到这一点,请告诉我),但我现在有一个类型问题。下面是我当前的代码(有些模板现在没有使用,比如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,而this是类型Association,由于元组的关系不能直接强制转换。请问做这件事的好方法是什么?
您可以为Relation
创建自己的get:
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);
}
}
现场演示。
相关文章:
- 关联容器的下界复杂性:成员函数与非成员函数
- C++GTKMM gui循环依赖关系
- std::future_error:无关联状态
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 查找自动生成键并具有线性内存消耗的小型关联数组
- Doxygen - 如何在不生成图形的情况下生成文本调用关系结果
- 如何在 OpenCV 中将图像与另一个图像相关联
- 删除提升存档对象也会删除与其关联的流?
- 变量如何以及在何处可能没有C++关联的名称?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 将正态随机变量与任意 RHO(corrcoef) 相关联
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 如何记住这种递归关系?
- 如何在头文件中声明类模板(由于循环依赖关系)
- 移动语义和深层/浅层复制之间有什么关系?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 对在不同二进制文件中创建的对象文件的依赖关系
- #include < conio.h> 和 getch() 方法之间的关系是什么?
- 我的聚合、关联和组合关系在这个C++程序中不起作用
- 如何使用元组修复多个关联关系