我在C ++中有一个可变参数的模板类(类似于std::tuple
)。实例化类时,我需要输入很多类型,例如
MyClass<int, int, double, double, double> my_obj;
当类型数较少时,此方法有效。但是,假设我有10个ints
,然后是20个doubles
,则键入它会很麻烦且容易出错。
C ++中是否存在一种机制,可以在template <>
参数中指定类型,然后指定出现次数?像这样:
MyClass<some_magic(int,2), some_magic(double, 3)> my_obj;
答案 0 :(得分:3)
这将使它成为
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>>
>);