ContainerBase::findChild()

This commit is contained in:
Robert Haschke 2019-02-20 11:14:50 +01:00
parent b364a8b5a2
commit 6de1c8dbe5
3 changed files with 33 additions and 0 deletions

View File

@ -51,6 +51,7 @@ public:
typedef std::unique_ptr<ContainerBase> pointer; typedef std::unique_ptr<ContainerBase> pointer;
size_t numChildren() const; size_t numChildren() const;
Stage* findChild(const std::string& name) const;
typedef std::function<bool(const Stage&, int depth)> StageCallback; typedef std::function<bool(const Stage&, int depth)> StageCallback;
/// traverse direct children of this container, calling the callback for each of them /// traverse direct children of this container, calling the callback for each of them

View File

@ -168,6 +168,21 @@ size_t ContainerBase::numChildren() const
return pimpl()->children().size(); return pimpl()->children().size();
} }
Stage* ContainerBase::findChild(const std::string& name) const
{
auto pos = name.find('/');
const std::string first = name.substr(0, pos);
for (const Stage::pointer& child : pimpl()->children())
if (child->name() == first)
{
if (pos == std::string::npos)
return child.get();
else if (auto *parent = dynamic_cast<const ContainerBase*>(child.get()))
return parent->findChild(name.substr(pos+1));
}
return nullptr;
}
bool ContainerBase::traverseChildren(const ContainerBase::StageCallback &processor) const bool ContainerBase::traverseChildren(const ContainerBase::StageCallback &processor) const
{ {
return pimpl()->traverseStages(processor, 0, 1); return pimpl()->traverseStages(processor, 0, 1);

View File

@ -100,6 +100,23 @@ TEST(ContainerBase, positionForInsert) {
EXPECT_EQ(impl->childByIndex(-4, true), impl->children().end()); EXPECT_EQ(impl->childByIndex(-4, true), impl->children().end());
} }
TEST(ContainerBase, findChild) {
SerialContainer s, *c2;
Stage *a, *b, *c1, *d;
s.insert(Stage::pointer(a=new NamedStage("a")));
s.insert(Stage::pointer(b=new NamedStage("b")));
s.insert(Stage::pointer(c1=new NamedStage("c")));
auto sub = Stage::pointer(c2 = new SerialContainer("c"));
c2->insert(Stage::pointer(d=new NamedStage("d")));
s.insert(std::move(sub));
EXPECT_EQ(s.findChild("a"), a);
EXPECT_EQ(s.findChild("b"), b);
EXPECT_EQ(s.findChild("c"), c1);
EXPECT_EQ(s.findChild("d"), nullptr);
EXPECT_EQ(s.findChild("c/d"), d);
}
template <typename Container> template <typename Container>
class InitTest : public ::testing::Test { class InitTest : public ::testing::Test {