Last active
April 16, 2017 21:13
-
-
Save alexnask/81dccfb2185f08aaf082b8d62711ba0f to your computer and use it in GitHub Desktop.
C++17 variant type checker trait.
This file contains hidden or 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
| // Variant type checker to make sure definition and implementation are in sync. | |
| template <typename VariantT, int Index, typename Current, typename... Args> | |
| struct check_variant_sub { | |
| inline static constexpr bool value = std::is_same_v<std::decay_t<decltype(std::get<Index>(std::declval<VariantT>()))>, Current> | |
| && check_variant_sub<VariantT, Index + 1, Args...>::value; | |
| }; | |
| template <typename VariantT, int Index, typename Last> | |
| struct check_variant_sub<VariantT, Index, Last> { | |
| inline static constexpr bool value = std::is_same_v<std::decay_t<decltype(std::get<Index>(std::declval<VariantT>()))>, Last>; | |
| }; | |
| template <typename VariantT, typename... Args> | |
| struct check_variant { | |
| inline static constexpr bool value = check_variant_sub<VariantT, 0, Args...>::value; | |
| }; | |
| template <typename VariantT, typename... Args> | |
| inline constexpr bool check_variant_v = check_variant<VariantT, Args...>::value; | |
| // Example: | |
| using Data = std::variant<std::string, double, DateTime>; | |
| static_assert(check_variant_v<Data, std::string, double, DateTime>); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment