Skip to content

Instantly share code, notes, and snippets.

@ktbarrett
Created November 15, 2023 20:35
Show Gist options
  • Save ktbarrett/16f0f6d38737a08ea3c9aa6bb2e46dc6 to your computer and use it in GitHub Desktop.
Save ktbarrett/16f0f6d38737a08ea3c9aa6bb2e46dc6 to your computer and use it in GitHub Desktop.
sum metafunction C++17
#include <variant>
template <typename ...Args>
struct sum_;
template <typename Last>
struct sum_<Last> {
using type = Last;
};
template <typename A, typename B, typename ...Rest>
struct sum_<A, B, Rest...> {
using type = typename sum_<std::variant<A, B>, Rest...>::type;
};
template <typename ...A, typename B, typename ...Rest>
struct sum_<std::variant<A...>, B, Rest...> {
using type = typename sum_<std::variant<A..., B>, Rest...>::type;
};
template <typename ...A, typename ...B, typename ...Rest>
struct sum_<std::variant<A...>, std::variant<B...>, Rest...> {
using type = typename sum_<std::variant<A..., B...>, Rest...>::type;
};
template <typename A, typename ...B, typename ...Rest>
struct sum_<A, std::variant<B...>, Rest...> {
using type = typename sum_<std::variant<A, B...>, Rest...>::type;
};
template <typename ...T>
using sum = typename sum_<T...>::type;
int main() {
using type_t = sum<int, char, double>;
using type_2 = sum<float, short>;
static_assert(
std::is_same_v<sum<int, char, double>, std::variant<int, char, double>>
);
static_assert(
std::is_same_v<
sum<type_t, float, short>,
std::variant<int, char, double, float, short>>);
static_assert(
std::is_same_v<
sum<type_t, type_2>,
std::variant<int, char, double, float, short>>);
static_assert(
std::is_same_v<
sum<int, char, type_2>,
std::variant<int, char, float, short>>);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment