LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
OptionalTableAs.h
Go to the documentation of this file.
1 #ifndef fhiclcpp_types_OptionalTableAs_h
2 #define fhiclcpp_types_OptionalTableAs_h
3 
4 #include "fhiclcpp/type_traits.h"
9 
10 #include <memory>
11 #include <string>
12 #include <utility>
13 
14 namespace fhicl {
15 
16  //==================================================================
17  // e.g. OptionalTableAs<T, Config> ====> T as created by convert(Config)
18  //
19  template <typename T, typename Config>
20  class OptionalTableAs {
21  public:
22  explicit OptionalTableAs(Name&& name);
23  explicit OptionalTableAs(Name&& name, Comment&& comment);
24  explicit OptionalTableAs(Name&& name,
25  Comment&& comment,
26  std::function<bool()> maybeUse);
27 
28  std::optional<T>
29  operator()() const
30  {
31  if (auto via = tableObj_()) {
32  return std::make_optional(convert(*via));
33  }
34  return std::nullopt;
35  }
36 
37  // Obsolete
38  bool
39  operator()(T& result) const
40  {
41  auto t = operator()();
42  if (t) {
43  result = *t;
44  }
45  return t.has_value();
46  }
47 
48  bool
49  hasValue() const
50  {
51  return tableObj_.hasValue();
52  }
53 
54  // Allow implicit conversion from TableAs to ParameterBase to
55  // access metadata of underlying fhicl-cpp type.
56  operator detail::ParameterBase const&() const noexcept { return tableObj_; }
57 
58  private:
60 
61  Comment
62  conversion_comment(Comment&& comment) const
63  {
64  std::string const preface =
65  "N.B. The following table is converted to type:";
66  std::string const name =
67  " '" + cet::demangle_symbol(typeid(T).name()) + "'";
68  std::string const user_comment =
69  comment.value.empty() ? "" : "\n\n" + comment.value;
70 
71  std::ostringstream oss;
72  oss << preface << '\n' << name << user_comment;
73 
74  return Comment{oss.str().c_str()};
75  }
76  };
77 
78  //==================================================================
79  // IMPLEMENTATION
80 
81  template <typename T, typename Config>
83  : OptionalTableAs{std::move(name), Comment("")}
84  {}
85 
86  template <typename T, typename Config>
88  : tableObj_{std::move(name), conversion_comment(std::move(comment))}
89  {}
90 
91  template <typename T, typename Config>
93  Comment&& comment,
94  std::function<bool()> maybeUse)
95  : tableObj_{std::move(name),
96  conversion_comment(std::move(comment)),
97  maybeUse}
98  {}
99 }
100 
101 #endif /* fhiclcpp_types_OptionalTableAs_h */
102 
103 // Local variables:
104 // mode: c++
105 // End:
Comment conversion_comment(Comment &&comment) const
OptionalTable< Config > tableObj_
OptionalTableAs(Name &&name)
parameter set interface
bool operator()(T &result) const
std::optional< T > operator()() const
bool hasValue() const
Definition: OptionalTable.h:62
std::string value
Definition: Comment.h:37