Skip to content

Instantly share code, notes, and snippets.

@nnaumenko
Created July 1, 2019 22:01
Show Gist options
  • Save nnaumenko/1db96f7e187979a057ee7ad757dee4f2 to your computer and use it in GitHub Desktop.
Save nnaumenko/1db96f7e187979a057ee7ad757dee4f2 to your computer and use it in GitHub Desktop.
Get numeric index for std::variant alternative with known type (at compile time) in C++17
#include <variant>
/// Get a numeric index for particular type included in variant type at compile time.
/// @tparam V Variant type to search for index.
/// @tparam T Type, index of which must be returned.
/// @return Index of type T in variant V; or variant size if V does not include an alternative for T.
template<typename V, typename T, size_t I = 0>
constexpr size_t variant_index() {
if constexpr (I >= std::variant_size_v<V>) {
return (std::variant_size_v<V>);
} else {
if constexpr (std::is_same_v<std::variant_alternative_t<I, V>, T>) {
return (I);
} else {
return (variant_index<V, T, I + 1>());
}
}
}
// Usage example below:
using MyVariant = std::variant<int, float, std::string>; //Index of int is 0, index of float is 1, index of std::string is 2
int main() {
static const auto variantSize = std::variant_size_v<MyVariant>;
if (const auto index = variant_index<MyVariant, int>(); index < variantSize) {
std::cout << "Index of int: " << index << "\n";
} else {
std::cout << "Variant does not contain int\n";
}
if (const auto index = variant_index<MyVariant, float>(); index < variantSize) {
std::cout << "Index of float: " << index << "\n";
} else {
std::cout << "Variant does not contain float\n";
}
if (const auto index = variant_index<MyVariant, std::string>(); index < variantSize) {
std::cout << "Index of std::string: " << index << "\n";
} else {
std::cout << "Variant does not contain std::string\n";
}
if (const auto index = variant_index<MyVariant, std::wstring>(); index < variantSize) {
std::cout << "Index of std::wstring: " << index << "\n";
} else {
std::cout << "Variant does not contain std::wstring\n";
}
if (const auto index = variant_index<MyVariant, char>(); index < variantSize) {
std::cout << "Index of char: " << index << "\n";
} else {
std::cout << "Variant does not contain char\n";
}
}
// Result:
// Index of int: 0
// Index of float: 1
// Index of std::string: 2
// Variant does not contain std::wstring
// Variant does not contain char
@ZamfirYonchev
Copy link

This was very useful.
I think the standard should define a way to obtain the index of an alternative at compile time.
This is could be one possible implementation.

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