Skip to content

Instantly share code, notes, and snippets.

@AndrewRademacher
Last active April 11, 2020 18:57
Show Gist options
  • Save AndrewRademacher/0d39f52e1174d324d8b0c095e87c98d9 to your computer and use it in GitHub Desktop.
Save AndrewRademacher/0d39f52e1174d324d8b0c095e87c98d9 to your computer and use it in GitHub Desktop.
#include <boost/callable_traits.hpp>
#include <fmt/format.h>
#include <tuple>
void increment_int(int a) { fmt::print("{}\n", a + 1); }
void increment_double(double a) { fmt::print("{}\n", std::pow(a, 2)); }
void increment_both(int a, double b) {
auto ia = a + 1;
auto ib = std::pow(b, 2);
fmt::print("{} + {} = {}\n", ia, ib, ia + ib);
}
const int default_int = 4;
const double default_double = 6;
template <typename DefaultType>
DefaultType get_default();
template <>
int get_default<int>() {
return default_int;
}
template <>
double get_default<double>() {
return default_double;
}
template <typename ParamTuple>
struct get_defaults;
template <typename... Params>
struct get_defaults<std::tuple<Params...>> {
std::tuple<Params...> operator()() { return std::make_tuple(get_default<Params>()...); }
};
template <typename Func>
void switch_(Func&& f) {
std::apply(std::forward<Func>(f), get_defaults<boost::callable_traits::args_t<Func>>()());
}
int main() {
switch_(&increment_int);
switch_(&increment_double);
switch_(&increment_both);
switch_(*[](int a) { fmt::print("Lambda a = {}\n", a); });
switch_([](int a) { fmt::print("Lambda a = {}\n", a); });
switch_([x = 3](int a) { fmt::print("Lambda a with capture = {}\n", a + x); });
return 0;
}
@AndrewRademacher
Copy link
Author

Program Output:

5
36.0
5 + 36.0 = 41.0

@AndrewRademacher
Copy link
Author

New Output:

5
36.0
5 + 36.0 = 41.0
Lambda a = 4
Lambda a = 4
Lambda a with capture = 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment