Groundwork for datamodel

This commit is contained in:
maelstrom 2024-10-01 22:08:21 +02:00
parent 3f51b9a28b
commit ddd89a2b6d
2 changed files with 66 additions and 0 deletions

View file

@ -0,0 +1,46 @@
#include "instance.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <vector>
std::optional<std::shared_ptr<Instance>> Instance::GetParent() {
if (!this->Parent.has_value() || this->Parent.value().expired())
return std::nullopt;
return this->Parent.value().lock();
}
void Instance::SetParent(std::optional<std::shared_ptr<Instance>> newParent) {
// Remove this instance from the existing parent
if (this->Parent.has_value() && !this->Parent.value().expired()) {
std::shared_ptr<Instance> parent = this->Parent.value().lock();
parent->children.erase(std::remove_if(parent->children.begin(), parent->children.end(), [this](std::shared_ptr<Instance> ptr) {
return ptr.get() == this;
}));
}
// Add self to
if (newParent.has_value()) {
newParent.value()->children.push_back(this->shared_from_this());
}
this->Parent = newParent;
}
std::vector<std::shared_ptr<Instance>> Instance::GetChildren() {
return this->children;
}
Instance Instance::CloneInternal() {
// TODO: Implement refs
Instance clone = *this;
clone.children = std::vector<std::shared_ptr<Instance>>();
clone.children.reserve(this->children.size());
for (std::shared_ptr<Instance> child : this->children) {
clone.children.push_back(std::make_shared<Instance>(child->CloneInternal()));
}
return clone;
}

20
src/datamodel/instance.h Normal file
View file

@ -0,0 +1,20 @@
#pragma once
#include <memory>
#include <optional>
#include <string>
#include <vector>
// The base class for all objects in the data model
class Instance : std::enable_shared_from_this<Instance> {
private:
std::optional<std::weak_ptr<Instance>> Parent;
std::vector<std::shared_ptr<Instance>> children;
public:
std::string Name;
std::optional<std::shared_ptr<Instance>> GetParent();
void SetParent(std::optional<std::shared_ptr<Instance>> newParent);
std::vector<std::shared_ptr<Instance>> GetChildren();
virtual void Init();
Instance CloneInternal();
};