Is there an std::variant that holds all variants
I am looking for a class that is like std::variant that holds all types instead of one of the types.
What you are looking for is called std::tuple
std::tuple<int,double> mytup( 1, 2.0 );
std::cout << std::get<int>( mytup ) << "\n"; // prints 1
std::cout << std::get<double>( mytup ) << "\n"; // prints 2
std::cout << std::get<std::string>( mytup ) << "\n"; // compiler error
Live example
As for single type appearance requirement you would get compilation error when you try to use std::get<type>
instead of index with std::tuple
with duplicated types. (thanks @max66)
In addition to Slava's answer, you can enforce type-uniqueness in a tuple using for example something like is_unique
from this post:
#include <tuple>
#include <type_traits>
// From https://stackoverflow.com/a/47511516
template <typename...>
inline constexpr auto is_unique = std::true_type{};
template <typename T, typename... Rest>
inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
(!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
>{};
// Tuple that only accept unique type parameters
template<typename... Ts>
using uniq_tuple = typename std::enable_if<is_unique<Ts...>, std::tuple<Ts...>>::type;
int main()
{
// Compiles
uniq_tuple<int, float> t1;
// Fails
uniq_tuple<int, float, int> t2;
return 0;
}