【问题标题】:Extract template template parameter and variadic template parameter from class template从类模板中提取模板模板参数和可变参数模板参数
【发布时间】:2018-08-04 14:52:44
【问题描述】:

给定以下类模板:

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&lt;c1&gt; 是从 c1 中提取模板模板参数的魔术技巧,vt_parameter&lt;c1&gt; 是提取其可变参数模板参数的魔术技巧。

为了提取模板模板参数,我尝试在container_type_holder 中添加一个别名,但这不起作用,因为它不是一个完整的类型。为了提取可变参数模板参数,我尝试了相同的策略,但没有成功。

template <template <typename... Args> class Container, typename... Args>
struct container_type_holder 
{
    using container = Container; // doesnt work
    using args = Args...; // ???
};

我不知道这是否可能,我是模板世界的初学者。

【问题讨论】:

  • using 指令仅适用于单一类型,但这里 Container 是未实例化的模板,Args... 是参数包。

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


【解决方案1】:

您可以使用这些别名来检索模板参数:

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>>>;

【讨论】:

    【解决方案2】:

    我认为这不可能你问什么,但是......你确定你不能写container_type_holder 只是接收一个类型

    template <typename>
    struct container_type_holder;
    

    并将您的结构开发为部分专业化?

    template <template <typename... Args> class Container, typename... Args>
    struct container_type_holder<Container<Args...>> 
     {
       // ...
     };
    

    这种方式是 container_type_holder 本身提取模板-模板参数和可变参数列表的特化方式

    我的意思是:如果你声明一个对象

    container_type_holder<std::map<std::string, int>>  obj;
    

    在专业化中,Containerstd::mapArgs...std::string, int

    【讨论】:

      猜你喜欢
      • 2019-11-22
      • 2016-12-01
      • 1970-01-01
      • 2014-09-08
      • 2014-04-12
      • 2016-01-22
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多