A header-only, unobtrusive, almighty alternative to the C++ switch statement that looks just like the original.

Overview

uberswitch

A header-only, unobtrusive, almighty alternative to the C++ switch statement that looks just like the original.

Sample usage (incomplete - see it working on godbolt: https://godbolt.org/z/WTx6K1)

// Enable nesting
#define UBERSWITCH_ALLOW_NESTING 1

// Include the tool 
#include <uberswitch/uberswitch.hpp>

// The holy grail of the switches: the string switch!
int string2num(std::string s) {
    uswitch (s) {
        ucase ("one"):
            return 1;

        ucase ("two"):
            return 2;

        ucase ("three"):
            return 3;

        // fallthrough works too
        ucase ("four"):
        ucase ("f0ur"):
            return 4;

        default: return -1;
    }
}
    
// More unexpected types work too
std::string pair2string(std::pair<int, int> p) {
    uswitch (p) {
        ucase (std::make_pair(1, 2)):
            return "12";

        // List initialization works too
        ucase ({3, 4}):
            return "34";

        default:
            return "Unknown pair";
    }
}

// You can actually switch over multiple items without packing them explicitly
// and the whole construct is constexpr!
constexpr const char* pair2string(int a, int b) {
    uswitch (a, b) {
        ucase (1, 2):
            return "12";

        ucase (3, 4):
            return "34";

        // And if you don't care about one of the items, you can use a wildcard
        ucase (uberswitch::any, 5):
            return "any5";
            
        // Fallthrough works as well.
        ucase (6, 7):
        ucase (8, 9):
            return "67 or 89";
            
        // And you can of course break out of the switch at any time.
        ucase (0, 0):
            break;
            
        default:
            return "Unknown (a,b)";
    }
    
    return "You found the code to break out!";
}

// Uberswitches can be nested if you define UBERSWITCH_ALLOW_NESTING to 1.
// In that case, fameta::counter will be used to get access to compile time scoped counters, which are needed for the nesting functionality.
constexpr const char* pair2string(int a, int b, int c) {
    uswitch (a, b) {
        ucase (1, 2):
            return "12";

        ucase (3, 4):
            return "34";

        default:
            // Starting a new uberswitch here!
            uswitch (a, c) {
                ucase (3, 5):
                    return "35";
                    
                // And you can of course also break out of a nested switch.
                ucase (0, 0):
                    break;

                default: 
                    return "Unknown (a,b)";
            }
            
            break;        
    }
    
    return "You found the code to break out!";
}

// Within the standard uberswitch the continue keyword acts just like the break keyword, which makes it unusable for its intended purpose.
// However, for those cases in which such a functionality is required, uberswitch_c and case_c can be used. 
// The trailing 'c' stands for 'context', which is an identifier or a number used as the first parameter of both and needs to be kept in synch between them. 
// Uberswitch_c and case_c cannot be used in constexpr functions and require c++17. This is a necessary cost to be able to use the continue keyword as it was intended.
std::string pairs_in_map(const std::map<int, std::string> &map) {
    std::string ret;
    
    for (const auto &p: map) {
        uswitch_c (M, p.first, p.second) {
            ucase_c (M, 1, "2"):
                ret.append("12");
                break;

            ucase_c (M, 3, "4"):
                ret.append("34");
                break;

            default:
                ret.append("[").append(std::to_string(p.first)).append(p.second).append("]");
                continue;
        }
        
        ret.append("-");
    }
        
    return ret;
}

// The above function, given the following map as input:
//
//     std::map<int, std::string> m {
//         { 2, "4"},
//         { 1, "2"},
//         { 5, "6"},
//         { 3, "4"},
//         { 7, "8"}
//    };
//
// Produces the following output:
//
//     12-[24]34-[56][78]    
You might also like...
gsl-lite – A single-file header-only version of ISO C++ Guidelines Support Library (GSL) for C++98, C++11, and later

gsl-lite: Guidelines Support Library for C++98, C++11 up metadata build packages try online gsl-lite is an implementation of the C++ Core Guidelines S

Bsl - Rust 2018 and C++20,
Bsl - Rust 2018 and C++20, "constexpr everything", AUTOSAR compliant header-only library intended to support the development of critical systems applications

Description The Bareflank Support Library (BSL) is a Rust 2018 and C++20, "constexpr everything", AUTOSAR compliant header-only library intended to su

jkds is a modern header-only C++20 library that complements the standard library.

jkds is a modern header-only C++20 library that complements the standard library. It provides generic atypical data structures, ergonomic functional programming abstractions, and then some.

Allows a programmer to print table-like outputs over std::ostream.

tableprinter Allows a programmer to print table-like outputs over std::ostream. It is a header only library. No other dependency than STL. Provides re

Improved and configurable drop-in replacement to std::function that supports move only types, multiple overloads and more

fu2::function an improved drop-in replacement to std::function Provides improved implementations of std::function: copyable fu2::function move-only fu

Library that simplify to find header for class from STL library.

Library that simplify to find header for class from STL library. Instead of searching header for some class you can just include header with the class name.

✔️The smallest header-only GUI library(4 KLOC) for all platforms
✔️The smallest header-only GUI library(4 KLOC) for all platforms

Welcome to GUI-lite The smallest header-only GUI library (4 KLOC) for all platforms. 中文 Lightweight ✂️ Small: 4,000+ lines of C++ code, zero dependenc

A massively spiffy yet delicately unobtrusive compression library.

ZLIB DATA COMPRESSION LIBRARY zlib 1.2.11 is a general purpose data compression library. All the code is thread safe. The data format used by the z

A free, offline Pokémon Home alternative for Switch!

Eevee A free, offline Pokémon Home alternative for Switch! Features currently available: Bank Cloning Editing Features planned: Editing LGPE support O

Play Nintendo Switch using an original N64 controller via an Arduino Uno!

N64 - Arduino Uno - Nintendo Switch Description By connecting an original N64 controller to an Arduino UNO R3 running this code, and plugging the US

Upgraded from Pixar postcard path tracing, instead of printing Pixar, this program print my name, which pose to be more challenging than the original code. The upgraded is also more readable and run 9x faster than the original source code.
Original hVNC has been recoded to work with all version of windows above XP. Thanks to the original author for this wonderful tool.

hVNC - Recoded This is the recoded version of the hVNC found in TinyNuke trojan. Compiling Compile tested with Visual Studio 2017. No compile errors.

a header-only, constexpr alternative to gperf for C++14 users

Frozen Header-only library that provides 0 cost initialization for immutable containers, fixed-size containers, and various algorithms. Frozen provide

RE2 is a fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python. It is a C++ library.

This is the source code repository for RE2, a regular expression library. For documentation about how to install and use RE2, visit https://github.co

BKM-10Rduino is an Arduino based alternative for the Sony BKM-10R control unit typically used with Sony broadcast monitors like the BVM-D20F1a/e/u
BKM-10Rduino is an Arduino based alternative for the Sony BKM-10R control unit typically used with Sony broadcast monitors like the BVM-D20F1a/e/u

BKM-10Rduino BKM-10Rduino is an Arduino (natch) based alternative for the Sony BKM-10R control unit typically used with Sony broadcast monitors like t

Minerva: a fast and flexible tool for deep learning on multi-GPU. It provides ndarray programming interface, just like Numpy. Python bindings and C++ bindings are both available. The resulting code can be run on CPU or GPU. Multi-GPU support is very easy. A scratch built kernel original planed to only render a Utah-teapot
A scratch built kernel original planed to only render a Utah-teapot

teapot-OS (sine wave animation) (first 3d renderer, with mouse controll) Current progress Bootloader enter 32 bit protected mode and run c code Switch

Just a basic mini library for parsing simple files that only have variables written and with Lua extension.

C++ Parser Lua file config Just a basic mini library for parsing simple files that only have variables written and with Lua extension. Note: At the mo

This is a prank windows malware, is only for fun, it's just for fun, it's not harmful
This is a prank windows malware, is only for fun, it's just for fun, it's not harmful

DBUSTER-PRO (C) 2021-2022 DioBrando This is a prank windows malware, just for fun, nothing harmful. I will teach you how to compile, and remove malwar

Owner
Fabio
Fabio
span lite - A C++20-like span for C++98, C++11 and later in a single-file header-only library

span lite: A single-file header-only version of a C++20-like span for C++98, C++11 and later Contents Example usage In a nutshell License Dependencies

Martin Moene 427 Dec 31, 2022
string_view lite - A C++17-like string_view for C++98, C++11 and later in a single-file header-only library

string_view lite: A single-file header-only version of a C++17-like string_view for C++98, C++11 and later Contents Example usage In a nutshell Licens

Martin Moene 357 Dec 28, 2022
variant lite - A C++17-like variant, a type-safe union for C++98, C++11 and later in a single-file header-only library

variant lite: A single-file header-only version of a C++17-like variant, a type-safe union for C++98, C++11 and later Contents Example usage In a nuts

Martin Moene 225 Dec 29, 2022
Single-header header-only C++11 / C++14 / C++17 library for easily managing set of auto-generated type-safe flags.

Single-header header-only C++11 / C++14 / C++17 library for easily managing set of auto-generated type-safe flags. Quick start #include <bitflags/bitf

Marin Peko 76 Nov 22, 2022
This project aims to recreate the behaviour of the original MacOS's printf

The printf function is one of the most versatile and well-known functions in the C language. From a testing aid to tabulation method, printf is a very powerful and important tool in every dev's kit. This project aims to recreate the behaviour of the original MacOS's printf, including its basic error management, some of its flags, minimum field width stipulation and most of its basic conversions.

Abdessamad Laamimi 8 Feb 15, 2022
This project is a copy of the original printf function of C langage.

ft_printf This project is a copy of the original printf function of C langage. Ft_printf (42cursus) 2021-2022 Actual Status : finished. Result : 100%

NABIL ATTIA 2 Dec 11, 2021
A collection of std-like single-header C++ libraries

itlib: iboB's Template Libraries A collection of small single-header C++ libraries similar to or extending the C++ standard library. See below for a l

Borislav Stanimirov 98 Dec 29, 2022
expected lite - Expected objects in C++11 and later in a single-file header-only library

expected lite: expected objects for C++11 and later expected lite is a single-file header-only library for objects that either represent a valid value

Martin Moene 254 Jan 4, 2023
gsl-lite – A single-file header-only version of ISO C++ Guidelines Support Library (GSL) for C++98, C++11, and later

gsl-lite: Guidelines Support Library for C++98, C++11 up metadata build packages try online gsl-lite is an implementation of the C++ Core Guidelines S

gsl-lite 774 Jan 7, 2023
Modern C++ generic header-only template library.

nytl A lightweight and generic header-only template library for C++17. Includes various utility of all kind that i needed across multiple projects: Ex

Jan 95 Nov 3, 2022