问题
Given the following class template:
template <template <typename... Args> class Container, typename... Args>
struct container_type_holder {};
I would like to extract its template template parameter and its variadic parameter to reuse in another context. Example:
using c1 = container_type_holder<std::map, std::string, int>;
using c2 = container_type_holder<tt_parameter<c1>, vt_parameter<c1>>;
Where tt_parameter<c1>
is some magic trick to extract the template template parameter from c1 and vt_parameter<c1>
to extract its variadic template parameter.
In order to extract the template template parameter I tried to add an alias inside container_type_holder
, but that didn't work because it is not a complete type. To extract the variadic template parameter I tried the same strategy but with no success.
template <template <typename... Args> class Container, typename... Args>
struct container_type_holder
{
using container = Container; // doesnt work
using args = Args...; // ???
};
I don't know if this is possible or not, I'm a begginer in the template world.
回答1:
You might use those aliases to be allowed to retrieve template parameters:
template <template <typename... Args> class Container,
typename... Args>
struct container_type_holder
{
template <typename ... Ts>
using container = Container<Ts...>;
constexpr std::size arg_count = sizeof...(Args);
using args_as_tuple = std::tuple<Args...>;
template <std::size_t I>
using get_arg = typename std::tuple_element<I, std::tuple<Args...>::type;
// And possibly helpers, such as
template <template <typename ...> OtherContainer>
using template_rebind = container_type_holder<OtherContainer, Args...>;
};
and then, usage might be:
using c1 = container_type_holder<std::map, std::string, int>;
using c2 = c1::template_rebind<std::unordered_map>;
using c3 = container_type_holder<std::vector, std::pair<c1::get_arg<0>, c1::get_arg<1>>>;
回答2:
I don't think it's possible what you ask but... are you sure you can't write the container_type_holder
simply receiving a type
template <typename>
struct container_type_holder;
and develop your struct as a partial specialization ?
template <template <typename... Args> class Container, typename... Args>
struct container_type_holder<Container<Args...>>
{
// ...
};
This way is the container_type_holder
specialization itself that extract the template-template paramenter and variadic list
I mean: if you declare an object
container_type_holder<std::map<std::string, int>> obj;
in the specialization you have that Container
is std::map
and that Args...
is std::string, int
.
来源:https://stackoverflow.com/questions/51680044/extract-template-template-parameter-and-variadic-template-parameter-from-class-t