BornAgain  1.19.79
Open-source research software to simulate and fit neutron and x-ray reflectometry and grazing-incidence small-angle scattering
NodeUtils.h
Go to the documentation of this file.
1 // ************************************************************************************************
2 //
3 // BornAgain: simulate and fit reflection and scattering
4 //
5 //! @file Param/Node/NodeUtils.h
6 //! @brief Defines collection of utility functions for INode.
7 //!
8 //! @homepage http://www.bornagainproject.org
9 //! @license GNU General Public License v3 or higher (see COPYING)
10 //! @copyright Forschungszentrum Jülich GmbH 2018
11 //! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
12 //
13 // ************************************************************************************************
14 
15 #ifdef SWIG
16 #error no need to expose this header to Swig
17 #endif
18 
19 #ifndef USER_API
20 #ifndef BORNAGAIN_PARAM_NODE_NODEUTILS_H
21 #define BORNAGAIN_PARAM_NODE_NODEUTILS_H
22 
23 #include "Base/Util/Assert.h"
24 #include "Param/Node/INode.h"
25 #include <string>
26 #include <vector>
27 
28 namespace NodeUtils {
29 
30 template <typename T>
31 std::vector<const T*> ChildNodesOfType(const INode& node)
32 {
33  std::vector<const T*> result;
34  for (const auto& p_child : node.nodeChildren()) {
35  if (const auto* t = dynamic_cast<const T*>(p_child))
36  result.push_back(t);
37  }
38  return result;
39 }
40 
41 template <typename T>
42 const T* OnlyChildOfType(const INode& node)
43 {
44  const auto list = ChildNodesOfType<T>(node);
45  if (list.size() != 1)
46  return nullptr;
47  return list.front();
48 }
49 
50 template <typename T>
51 std::vector<const T*> AllDescendantsOfType(const INode& node)
52 {
53  std::vector<const T*> result;
54  for (const auto* child : node.nodeChildren()) {
55  ASSERT(child);
56  if (const auto* t = dynamic_cast<const T*>(child))
57  result.push_back(t);
58  for (const auto* t : AllDescendantsOfType<T>(*child))
59  result.push_back(t);
60  }
61  return result;
62 }
63 
64 } // namespace NodeUtils
65 
66 #endif // BORNAGAIN_PARAM_NODE_NODEUTILS_H
67 #endif // USER_API
Defines the macro ASSERT.
#define ASSERT(condition)
Definition: Assert.h:45
Defines interface INode.
Base class for tree-like structures containing parameterized objects.
Definition: INode.h:40
virtual std::vector< const INode * > nodeChildren() const
Returns all children.
Definition: INode.cpp:56
std::vector< const T * > ChildNodesOfType(const INode &node)
Definition: NodeUtils.h:31
std::vector< const T * > AllDescendantsOfType(const INode &node)
Definition: NodeUtils.h:51
const T * OnlyChildOfType(const INode &node)
Definition: NodeUtils.h:42