Skip to content

Instantly share code, notes, and snippets.

@qrealka
Last active October 17, 2019 14:41
Show Gist options
  • Save qrealka/4018279f5c6f87038311406886f59e55 to your computer and use it in GitHub Desktop.
Save qrealka/4018279f5c6f87038311406886f59e55 to your computer and use it in GitHub Desktop.
generate error messages functions
#include <string>
#include <fmt/format.h>
#include <fmt/printf.h>
namespace details
{
#define ERROR_MESSAGES(X) \
X(DivByZero) \
X(NumOverflow) \
/****/
#define DEFINE_MESSAGE_ID(X) X,
enum class MessageId : int {
Invalid = -1,
ERROR_MESSAGES(DEFINE_MESSAGE_ID)
};
#undef DEFINE_MESSAGE_ID
struct literal
{
template<size_t N>
constexpr literal(const char (&str)[N]) : data{str}, size{N-1}{}
const char* const data;
const size_t size;
};
constexpr const literal allMessages[] = {
// todo: move to include file
"Divizion by zero {:d}/{:d}",
"Numeric overflow for expression {}",
};
} // namespace details
#define DEFINE_FORMAT_FUNC(X) \
template<typename... Args> \
auto format ## X (Args&&... args) { \
return fmt::format( \
[] { \
struct str : fmt::compile_string { \
using char_type = char; \
constexpr operator fmt::string_view() const {\
using namespace details; \
return {allMessages[(int)MessageId::X].data, allMessages[(int)MessageId::X].size}; \
}} result; \
return result; \
}(), \
std::forward<Args>(args)...);\
}
ERROR_MESSAGES(DEFINE_FORMAT_FUNC)
#define COMPILE_ERRORS 0
int main()
{
#if COMPILE_ERRORS
fmt::print( formatDivByZero(2, 1.0) );
//fmt::print( formatDivByZero(2) );
//fmt::print( formatNumOverflow(1,2,3,4));
#else
fmt::print( formatDivByZero(2,0) );
fmt::print( formatNumOverflow("111111111111111111111111111111 * 10"));
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment