c++ - 从类模板中提取模板模板参数和可变模板参数

标签 c++ c++11 templates variadic-templates template-meta-programming

给定以下类模板:

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/

相关文章:

c++ - Boost图形库,修复节点大小

c++ - C++自定义范围类型MSVC可以编译,但G++不能

c++ - 转发引用始终被视为右值引用

c++ - 作为类成员的通用 shared_ptr

c++ - 如何定义模板类模板友元函数,其参数之一是模板类主体之外的依赖名称?

C++ boost : Any gotchas with BOOST_FOREACH?

c++ - 从文件中读取数字到两位有效数字?

c++ - 为什么 C++11 中仍然需要 "using"指令来从基类中引入在派生类中重载的方法

c++ - 需要帮助在 C++ 中使用 stringstream 在一行中输入多个整数

c++ - 在 C++ 中使用枚举作为模板类型参数