Reputation: 3824
I have a variadic template class in C++ (similar to std::tuple
). When instantiating the class, I need to type a lot of types, e.g.
MyClass<int, int, double, double, double> my_obj;
This approach works when the number of types is small. However, say if I have 10 ints
followed by 20 doubles
, typing it would be cumbersome and error-prone.
Is there is mechanism in C++, to specify types followed by number of occurrence in the template <>
argument? Something like this:
MyClass<some_magic(int,2), some_magic(double, 3)> my_obj;
Upvotes: 0
Views: 111
Reputation: 11250
This will make it:
namespace detail{
template <class T, auto> using always_t = T;
template <class T, std::size_t... Idx>
auto repeat_impl(std::index_sequence<Idx...>) -> std::tuple<always_t<T, Idx>...>;
template <class T, class...>
struct pack
{
using type = T;
};
template <class... T, class... R, class... Tuple>
struct pack<std::tuple<T...>, std::tuple<R...>, Tuple...>
: pack<std::tuple<T..., R...>, Tuple...>
{ };
template <class> struct tuple_to_class;
template <class... T> struct tuple_to_class<std::tuple<T...>>
{
using type = MyClass<T...>;
};
}
template <class T, std::size_t N>
using repeat_t = decltype(detail::repeat_impl<T>(std::make_index_sequence<N>{}));
template <class... Repeats>
using ToMyClass = typename detail::tuple_to_class<typename detail::pack<Repeats...>::type>::type;
using C = MyClass<int, int, double, double, double>;
static_assert(std::is_same_v<C,
ToMyClass<repeat_t<int, 2>, repeat_t<double, 3>>
>);
Upvotes: 3