Skip to content
Snippets Groups Projects
Commit 6c915467 authored by Niclas Esser's avatar Niclas Esser
Browse files

New utility function in DadaHeader specialized get() with returning a default...

New utility function in DadaHeader specialized get() with returning a default vault value, when key does not exists. safe_set() for passing optionals
parent e5cdf4ca
No related branches found
No related tags found
No related merge requests found
Pipeline #265258 passed
......@@ -80,6 +80,20 @@ class DadaHeader
template <typename T>
[[nodiscard]] T get(std::string_view key) const;
/**
* @brief Get a value from the header. If the key in the header does not exists it returns a default
*
* @param key An ASCII key (the name of the value to get)
* @param default_value The default value which should get returned
*
* @tparam T The data type of the parameter to be read
*
* @return The value corresponding to the given key or default value
*/
template <typename T>
[[nodiscard]] T get(std::string_view key, T default_value) const;
/**
* @brief Get an optional value from the header
*
......@@ -142,6 +156,18 @@ class DadaHeader
*/
void set(std::string_view key, std::string const& value);
/**
* @brief Sets a dada key based on an optional. If the optional is empty, it sets the default_value
*
* @param key An ASCII key (the name of the value to be set)
* @param[in] opt The std::optional containing a value or std::nullopt
* @param default_value The default value which is written when the optional is empty
*/
template<typename T>
void safe_set(std::string_view key,
const std::optional<T>& opt,
const T& default_value);
/**
* @brief Set a value in the header from a container
*
......
......@@ -50,6 +50,19 @@ void DadaHeader::set(std::string_view key,
_header_map[std::string{key}] = ss.str();
}
template<typename T>
void DadaHeader::safe_set(std::string_view key,
const std::optional<T>& opt,
const T& default_value)
{
if (opt) {
this->set(key, *opt);
} else {
this->set(key, default_value);
}
}
// Helper function for converting tokens
template <typename T>
T DadaHeader::convert_token(std::string_view token) const
......@@ -127,6 +140,16 @@ T DadaHeader::get(std::string_view key) const
return convert_token<T>(value);
}
template <typename T>
T DadaHeader::get(std::string_view key, T default_value) const
{
if (has_key(key)) {
return {get<T>(key)};
} else {
return default_value;
}
}
// Single-value getter
template <typename T>
std::optional<T> DadaHeader::get_optional(std::string_view key) const
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment