OscProb
exceptions.h
Go to the documentation of this file.
1#ifndef EXCEPTIONS_H
2#define EXCEPTIONS_H
3
4#include <sstream>
5#include <stdexcept>
6#include <string>
7#include <vector>
8
9namespace OscProb {
10 //.............................................................................
21 inline std::vector<std::string> split(const std::string& s, char delimiter)
22 {
23 std::string token;
24 std::vector<std::string> tokens;
25 std::istringstream tokenStream(s);
26 while (std::getline(tokenStream, token, delimiter)) {
27 // Trim leading/trailing whitespace
28 size_t first = token.find_first_not_of(" \t\n\r");
29 if (std::string::npos != first) {
30 size_t last = token.find_last_not_of(" \t\n\r");
31 tokens.push_back(token.substr(first, (last - first + 1)));
32 }
33 else {
34 tokens.push_back("");
35 }
36 }
37 return tokens;
38 }
39
40 //.............................................................................
54 template <typename... Args>
55 std::string format_args(const std::string& names, const Args&... args)
56 {
57 std::stringstream ss;
58
59 std::vector<std::string> arg_names = split(names, ',');
60
61 std::size_t i = 0;
62 // Lambda to iterate and print each argument.
63 auto printer = [&](const auto& arg_value) {
64 if (i < arg_names.size()) {
65 if (i > 0) ss << ", ";
66 ss << arg_names[i] << " = " << arg_value;
67 }
68 i++;
69 };
70 // Unpack the arguments and print them using the lambda.
71 (printer(args), ...);
72
73 return ss.str();
74 }
75} // namespace OscProb
76
77// Macro to get the most descriptive function name available
78#if defined(__GNUC__) || defined(__clang__)
79#define FUNCTION_NAME __PRETTY_FUNCTION__
80#elif defined(_MSC_VER)
81#define FUNCTION_NAME __FUNCSIG__
82#else
83#define FUNCTION_NAME __func__
84#endif
85
86// The core macro for throwing an exception with detailed info
87#define THROW_ON_INVALID_ARG(condition, ...) \
88 do { \
89 if (!(condition)) { \
90 std::stringstream ss; \
91 ss << "\n Condition '" << #condition << "' failed." \
92 << "\n With: " << OscProb::format_args(#__VA_ARGS__, __VA_ARGS__) \
93 << "\n In function: " << FUNCTION_NAME \
94 << "\n At file: " << __FILE__ << "\n At line: " << __LINE__; \
95 throw std::invalid_argument(ss.str()); \
96 } \
97 } \
98 while (0)
99
100#endif // EXCEPTIONS_H
Some useful general definitions.
Definition: Absorption.h:6
std::string format_args(const std::string &names, const Args &... args)
The main variadic template function to log the arguments.
Definition: exceptions.h:55
std::vector< std::string > split(const std::string &s, char delimiter)
Helper function to split a string by a delimiter.
Definition: exceptions.h:21