给定以下类模板:
template <template <typename... Args> class Container, typename... Args>
struct container_type_holder {};
我想提取其模板模板参数及其可变参数以在另一个上下文中重用。示例:
using c1 = container_type_holder<std::map, std::string, int>;
using c2 = container_type_holder<tt_parameter<c1>, vt_parameter<c1>>;
在哪里tt_parameter<c1>
是从 c1 和 vt_parameter<c1>
中提取模板模板参数的一些魔术提取其可变模板参数。
为了提取模板模板参数,我尝试在 container_type_holder
中添加一个别名,但这没有用,因为它不是一个完整的类型。为了提取可变参数模板参数,我尝试了相同的策略但没有成功。
template <template <typename... Args> class Container, typename... Args>
struct container_type_holder
{
using container = Container; // doesnt work
using args = Args...; // ???
};
我不知道这是否可能,我是模板世界的初学者。
最佳答案
您可以使用这些别名来检索模板参数:
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...>;
};
然后,用法可能是:
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>>>;
关于c++ - 从类模板中提取模板模板参数和可变模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51680044/