From 44c7da77b76b1820a395b7017b128d3c907b5dbe Mon Sep 17 00:00:00 2001 From: Thomas Fischer <thomas.fischer@ufz.de> Date: Thu, 30 Apr 2020 13:09:44 +0200 Subject: [PATCH] [BL] Impl. helper fct. template substituteKeyword. --- BaseLib/FileTools.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/BaseLib/FileTools.cpp b/BaseLib/FileTools.cpp index 51daf0cfd3f..f22ab184714 100644 --- a/BaseLib/FileTools.cpp +++ b/BaseLib/FileTools.cpp @@ -12,6 +12,9 @@ * */ +#include <unordered_map> +#include <typeindex> + #include "FileTools.h" #include "Error.h" #include "filesystem.h" @@ -70,6 +73,41 @@ std::string containsKeyword(std::string const& str, std::string const& keyword) return ""; } +template <typename T> +bool substituteKeyword(std::string& result, std::string& parenthesized_string, + std::string::size_type begin, std::string::size_type end, + std::string const& keyword, T& data) +{ + std::string precision_specification = + containsKeyword(parenthesized_string, keyword); + + if (precision_specification.empty()) + { + return false; + } + + std::unordered_map<std::type_index, char> type_specification; + type_specification[std::type_index(typeid(int))] = 'd'; + type_specification[std::type_index(typeid(double))] = 'f'; // default + type_specification[std::type_index(typeid(std::string))] = 's'; + + auto const& b = precision_specification.back(); + // see https://fmt.dev/latest/syntax.html#formatspec + if (b == 'e' || b == 'E' || b == 'f' || b == 'F' || b == 'g' || b == 'G') + { + type_specification[std::type_index(typeid(double))] = b; + precision_specification = precision_specification.substr( + 0, precision_specification.length() - 1); + } + + std::string const generated_fmt_string = + "{" + precision_specification + + type_specification[std::type_index(typeid(data))] + "}"; + result = result.substr(0, begin) + fmt::format(generated_fmt_string, data) + + result.substr(end + 1, result.length() - (end + 1)); + return true; +} + std::string constructFileName(std::string const& prefix, int const process_id, int const timestep, -- GitLab