[英]In C++ template arguments, is it possible to specify the type and number of occurrence of that type?
I have a variadic template class in C++ (similar to std::tuple
). 我在C ++中有一个可变参数模板类(类似于std::tuple
)。 When instantiating the class, I need to type a lot of types, eg 在实例化类时,我需要键入很多类型,例如
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. 但是,如果我有10个ints
后跟20个doubles
,那么输入它会很麻烦并且容易出错。
Is there is mechanism in C++, to specify types followed by number of occurrence in the template <>
argument? C ++中是否存在机制,在template <>
参数中指定类型后跟出现次数? Something like this: 像这样的东西:
MyClass<some_magic(int,2), some_magic(double, 3)> my_obj;
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>>
>);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.