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