Hacker News new | ask | show | jobs
by Rangi42 2014 days ago
With C++17's compile-time conditionals, plus good old C preprocessor macros, you could do this:

    #define MATCH_VARIANT(x) [](auto& x)
    #define CASE_VARIANT(x, T) constexpr (std::is_same_v<std::decay_t<decltype(x)>, T>)
    
    MATCH_VARIANT(arg) {
        if CASE_VARIANT(arg, string) {
            printf("string: %s\n", arg.c_str());
            // ...
        }
        else if CASE_VARIANT(arg, int) {
            printf("integer: %d\n", arg);
            // ...
        }
        else if CASE_VARIANT(arg, bool) {
            printf("bool: %d\n", arg);
            // ...
        }
    }
(MATCH_VARIANT could be extended to allow capturing vairables, or just omit that macro, it saves less typing than CASE_VARIANT anyway.)