EDIT
Лучший код был предложен Jarod42 в этой теме . Стиль C ++ 17:
#include <algorithm>
#include <tuple>
#include <vector>
class BaseObject {
public:
virtual ~BaseObject() = default;
virtual std::vector<BaseObject*> getAllParents() const = 0;
virtual std::vector<BaseObject*> getAllChildren() const = 0;
virtual void removeAllParents() = 0;
virtual void removeAllChildren() = 0;
};
template<typename TParentTuple, typename TChilderenTuple>
class Obj;
template<typename... ParentTags,
typename... ChildTags>
class Obj<std::tuple<ParentTags...>, std::tuple<ChildTags...>> : public BaseObject
{
std::tuple<std::vector<typename ParentTags::obj_type*>...> parents;
std::tuple<std::vector<typename ChildTags::obj_type*>...> children;
public:
template <typename T>
void addParent(T* parent) { std::get<std::vector<T*>>(parents).push_back(parent); }
template <typename T>
void removeParent(const T* parent) {
auto& v = std::get<std::vector<T*>>(parents);
auto it = std::find(std::cbegin(v), std::cend(v), parent);
if (it != std::cend(v)) { v.erase(it); }
}
template <typename T>
void addChild(T* child) { std::get<std::vector<T*>>(children).push_back(child); }
template <typename T>
void removeChild(const T* child) {
auto& v = std::get<std::vector<T*>>(children);
auto it = std::find(std::cbegin(v), std::cend(v), child);
if (it != std::cend(v)) { v.erase(it); }
}
std::vector<BaseObject*> getAllParents() const override {
std::vector<BaseObject*> res;
std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
parents);
return res;
}
std::vector<BaseObject*> getAllChildren() const override {
std::vector<BaseObject*> res;
std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
children);
return res;
}
void removeAllParents() override {
std::apply(
[this](auto&... v)
{
[[maybe_unused]] auto clean = [this](auto& v) {
for (auto* parent : v) {
parent->removeChild(this);
}
v.clear();
};
(clean(v), ...);
},
parents);
}
void removeAllChildren() override {
std::apply(
[this](auto&... v)
{
[[maybe_unused]] auto clean = [this](auto& v) {
for (auto* child : v) {
child->removeParent(this);
}
v.clear();
};
( clean(v), ...);
},
children);
}
};
struct Human_tag;
struct Tree_tag;
struct Dog_tag;
struct Parasite_tag;
using Human = Obj<std::tuple<>, std::tuple<Tree_tag, Dog_tag>>;
using Tree = Obj<std::tuple<Human_tag>, std::tuple<>>;
using Dog = Obj<std::tuple<Human_tag>, std::tuple<Parasite_tag>>;
using Parasite = Obj<std::tuple<Dog_tag>, std::tuple<>>;
struct Human_tag { using obj_type = Human; };
struct Tree_tag { using obj_type = Tree; };
struct Dog_tag { using obj_type = Dog; };
struct Parasite_tag { using obj_type = Parasite; };
template<class A, class B>
void addRelation(A* a, B* b)
{
a->addChild(b);
b->addParent(a);
}
#include <iostream>
int main() {
Human h1;
Dog d1, d2;
addRelation(&h1, &d1);
addRelation(&h1, &d2);
auto result = h1.getAllChildren();
std::cout << result.size() << "\n"; //print 2
d1.removeAllParents();
result = h1.getAllChildren();
std::cout << result.size() << "\n"; //print 1
}
Старый код: (моя попытка)
ОК, поскольку вы не хотели дублировать код, я использовал этот проект как свой первый опыт работы с метапрограммированием / вариационными шаблонами. Вот что я получил:
#include <tuple>
#include <vector>
#include <algorithm>
template<class T>
using prtVector = std::vector<T*>;
// Interface, as required by assignment
class BaseObject {
public:
virtual ~BaseObject() {}
virtual prtVector<BaseObject> getAllParents() const = 0;
virtual prtVector<BaseObject> getAllChildren() const = 0;
virtual void removeAllParents() = 0;
virtual void removeAllChildren() = 0;
};
// base prototype
template<typename TOwnTag, typename TParentTagsTuple, typename TChildTagsTuple>
class Obj;
// Parent-type deduction
template<typename TOwnTag, typename TParentTag, typename... TParentTags, typename... TChildTags>
class Obj<TOwnTag, std::tuple<TParentTag, TParentTags...>, std::tuple<TChildTags...>>
: public Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>
{
// local types
using TOwn = typename TOwnTag::obj_type;
using TParent = typename TParentTag::obj_type;
// container
prtVector<TParent> parentsPtrs;
//befriend types
friend class Obj;
template<class A, class B>
friend void addRelation(A* const a, B* const b);
protected:
// prevent base function hiding with 'using'-declaration
using Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::addParent;
using Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeParent;
// add and remove element functions
void addParent(TParent* const parentPtr) { parentsPtrs.push_back(parentPtr); }
void removeParent(TParent const* const parentPtr) {
auto it = std::find(std::cbegin(parentsPtrs), std::cend(parentsPtrs), parentPtr);
if (it != std::cend(parentsPtrs)) parentsPtrs.erase(it);
}
public:
virtual ~Obj() {}
virtual prtVector<BaseObject> getAllParents() const override {
auto result = Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::getAllParents();
result.insert(std::begin(result), std::cbegin(parentsPtrs), std::cend(parentsPtrs));
return result;
}
virtual prtVector<BaseObject> getAllChildren() const override {
return Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::getAllChildren();
}
virtual void removeAllParents() override {
Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeAllParents();
for (auto&& parent : parentsPtrs) parent->removeChild(reinterpret_cast<TOwn* const>(this));
}
virtual void removeAllChildren() override {
Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeAllChildren();
}
};
// Child-type deduction
template<typename TOwnTag, typename TChildTag, typename... TChildTags>
class Obj<TOwnTag, std::tuple<>, std::tuple<TChildTag, TChildTags...>>
: public Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>
{
// local types
using TOwn = typename TOwnTag::obj_type;
using TChild = typename TChildTag::obj_type;
// container
prtVector<TChild> childrenPtrs;
//befriend types
friend class Obj;
template<class A, class B>
friend void addRelation(A* const a, B* const b);
protected:
// empty functions required for 'using'-declaration
void addParent() {}
void removeParent() {}
// prevent base function hiding with 'using'-declaration
using Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::addChild;
using Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::removeChild;
// add and remove element functions
void addChild(TChild* const childPtr) { childrenPtrs.push_back(childPtr); }
void removeChild(TChild const* const childPtr) {
auto it = std::find(std::cbegin(childrenPtrs), std::cend(childrenPtrs), childPtr);
if (it != std::cend(childrenPtrs)) childrenPtrs.erase(it);
}
public:
virtual ~Obj() {}
virtual prtVector<BaseObject> getAllParents() const override {
return Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::getAllParents();
}
virtual prtVector<BaseObject> getAllChildren() const override {
auto result = Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::getAllChildren();
result.insert(std::begin(result), std::cbegin(childrenPtrs), std::cend(childrenPtrs));
return result;
}
virtual void removeAllParents() override {}
virtual void removeAllChildren() override {
Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::removeAllChildren();
for (auto&& child : childrenPtrs) child->removeParent(reinterpret_cast<TOwn* const>(this));
}
};
// terminator
template<typename TOwnTag>
class Obj<TOwnTag, std::tuple<>, std::tuple<>> : public BaseObject {
protected:
// empty functions required for 'using'-declaration
void addChild() {}
void removeChild() {}
void addParent() {}
void removeParent() {}
public:
virtual ~Obj() {}
virtual prtVector<BaseObject> getAllParents() const override {
return prtVector<BaseObject>();
}
virtual prtVector<BaseObject> getAllChildren() const override {
return prtVector<BaseObject>();
}
virtual void removeAllParents() override {}
virtual void removeAllChildren() override {}
};
//prototype class tags
struct Human_tag;
struct Tree_tag;
struct Dog_tag;
struct Parasite_tag;
//define class types
using Human = Obj<Human_tag, std::tuple<>, std::tuple<Tree_tag, Dog_tag>>;
using Tree = Obj<Tree_tag, std::tuple<Human_tag>, std::tuple<>>;
using Dog = Obj<Dog_tag, std::tuple<Human_tag>, std::tuple<Parasite_tag>>;
using Parasite = Obj<Parasite_tag, std::tuple<Dog_tag>, std::tuple<>>;
//couple tags to classes
struct Human_tag { using obj_type = Human; };
struct Tree_tag { using obj_type = Tree; };
struct Dog_tag { using obj_type = Dog; };
struct Parasite_tag { using obj_type = Parasite; };
//(befriend)helper function
// maybe could do somehting with std::enable_if
// i.e. "enable if type B is in child tuple of A and
// type A is in parent tuple of B"
// that way the parser will already detect a relation is not possible
template<class A, class B>
void addRelation(A* const a, B* const b)
{
a->addChild(b);
b->addParent(a);
}
// now for some testing
#include <iostream>
int main() {
Human h1;
Dog d1, d2;
Parasite p1;
addRelation(&h1, &d1);
addRelation(&h1, &d2);
addRelation(&d1, &p1);
//addRelation(&h1, &p1); // compiler error
auto result = h1.getAllChildren();
std::cout << result.size() << "\n"; //print 2
d1.removeAllParents();
result = h1.getAllChildren();
std::cout << result.size() << "\n"; //print 1
std::cin.ignore();
}
Пожалуйста, задавайте вопросы обо всем, что неясно, потому что я изучил так много нового за последние 24 часа, что я не знаю, с чего начать с моего объяснения.