Created
November 15, 2023 20:35
-
-
Save ktbarrett/16f0f6d38737a08ea3c9aa6bb2e46dc6 to your computer and use it in GitHub Desktop.
sum metafunction C++17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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