Skip to content

Instantly share code, notes, and snippets.

@pnck
Created April 23, 2024 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pnck/eee96898f0d2e332fad5c9b1b0c0676e to your computer and use it in GitHub Desktop.
Save pnck/eee96898f0d2e332fad5c9b1b0c0676e to your computer and use it in GitHub Desktop.
if(a==1) return 1 DO MAKE SENSE in C++
// fun thing that `if a==1 f(1);if a==2 f(2)` do make sense in c++
#include <cstdint>
#include <format>
#include <iostream>
#include <string_view>
#include <tuple>
using namespace std;
enum E : int {
FOO = 0,
BAR,
BAZ,
};
#define MAP(K, ...) \
case K: { \
return __VA_ARGS__; \
}
#define MAP_BEGIN_WITH(V) switch (V) {
#define MAP_END() \
default: \
return {0, {"", "name=Anonymous"}}; \
}
consteval auto static_map(E e) -> tuple<id_t, tuple<string_view, string_view>> {
MAP_BEGIN_WITH(e)
MAP(FOO, {1234, {"FOO", "name=Foo"}})
MAP(BAR, {2345, {"BAR", "name=Bar"}})
MAP(BAZ, {34567, {"BAZ", "name=Baz"}})
MAP_END()
}
// this function may not be as easy as you've thought
void print_static_map(E e) {
static_map(FOO); // work
// static_map(e); // can't work
// this lambda is conteval, thus the static_map() work
auto flatten = [](E _e) consteval {
auto [id, extra] = static_map(_e);
auto [name, info] = std::move(extra);
return make_tuple(static_cast<int>(_e), id, name, info);
};
flatten(FOO); // work because called with constexpr
// flatten(e); // can't work
// now it's time to play with the "dumb forwarding"
auto to_runtime = [](auto f, E _e) {
switch (_e) {
case FOO:
return f(FOO);
case BAR:
return f(BAR);
case BAZ:
return f(BAZ);
default:
return f(E(-1));
}
};
cout << std::apply(
[](auto &&...args) {
return std::format("in case {}, id {} (name:{}) has info: {}\n",
args...);
},
// flatten(FOO)); // work, but only with literal
to_runtime(flatten, e)); // work at runtime
}
int main() {
print_static_map(FOO);
print_static_map(BAR);
print_static_map(BAZ);
print_static_map(E(-1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment