Do tej pory tylko związki stosowane do przechowywania każde z państw człon A lub B.
ja teraz znajduję się w przypadku, gdy chcę zmiany zużyty zarejestrował podczas wykonywania.
C++ Unia
union NextGen {
std::shared_ptr<TreeRecord> Child = nullptr;
std::vector<std::shared_ptr<TreeRecord>> Children;
};
Mój obecny Wykorzystanie:
void TreeRecord::AddChild(const std::shared_ptr<TreeRecord>& NewChild) {
if(_childCount == 0) {
_nextGeneration.Child = NewChild;
_childCount++;
} else if(_childCount == 1) {
//This is not clear to me:
//Do I have to set Child to nullptr first?
//Do I need to clear the Children vecor?
//Or will it work like this?
_nextGeneration.Children.push_back(_nextGeneration.Child);
_nextGeneration.Children.push_back(NewChild);
_childCount++;
} else {
_nextGeneration.Children.push_back(NewChild);
_childCount++;
}
}
Nowa realizacja (spróbuj):
typedef std::shared_ptr<TreeRecord> singlechild_type;
typedef std::vector<std::shared_ptr<TreeRecord>> children_type;
union {
singlechild_type _child;
children_type _children;
};
void TreeRecord::AddChild(const singlechild_type& NewChild) {
if(_childCount == 0) {
_child = NewChild;
_childCount = 1;
} else if(_childCount == 1) {
singlechild_type currentChild = _child; //Copy pointer
_child.~singlechild_type(); //Destruct old union member
new (&_children) children_type(); //Construct new union member
_children.push_back(currentChild); //Add old child to vector
_children.push_back(NewChild); //Add new child to vector
_childCount = 2;
} else {
_children.push_back(NewChild);
_childCount++;
}
}
Nawet o tym nie pomyślał! Co masz na myśli przez "ogólnie"? –
To jest poprawna odpowiedź, ale byłoby miło, gdybyś ją rozwinął. – mostruash
Nie będę miał jednego wektora elem. Używam Child dla 0 lub 1 elem i przełączam się na wektor dla więcej niż 1 elem. Czy popełniłem błąd ...? (Wciąż czytam twój kod) I używam oznaczonego związku, po prostu nie z boolowskim identyfikatorem, ale z "size_t _childCount", który wynosi 0 lub 1, gdy dziecko jest używane. –