【问题标题】:Using template programming to change the type of the container使用模板编程改变容器的类型
【发布时间】:2020-12-20 23:30:49
【问题描述】:

我一直在阅读模板元编程教程,我对那本书中的这个例子感到震惊。

 /* Change the type container */
  template<class NewList, class List>
  struct rename_container;
  
  template<template<class...> class NewList,
           template<class...> class List,
           class... Elements>
  struct rename_container<NewList, List<Elements...>>
  {
      using new_list = NewList<Elements...>;
  };

  int main()
  {
      rename_container<std::variant, std::tuple<int, float, double>> v;
      return 0;
  }

我收到以下错误以及其他错误。

type_containers.cpp:52:50: error: type/value mismatch at argument 1 in template parameter list for ‘template<class NewList, class List> struct rename_container’
 struct rename_container<NewList, List<Elements...>>
                                                  ^~
type_containers.cpp:52:50: note:   expected a type, got ‘NewList’

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 主模板rename_container 需要两个类型参数,但特化尝试使用模板参数。那是行不通的。我不确定这个例子应该实现什么,这对我来说没有多大意义。
  • 您希望 template&lt;template&lt;class...&gt; class NewList, class List&gt; struct rename_container; 作为主模板。
  • 你的意思可能是like this。 Sill 看起来毫无意义,但至少它可以编译。

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


【解决方案1】:

好像有错别字,应该是

/* Change the type container */
  template<template<class...> class NewList, class List>
  struct rename_container;

而且可能:

rename_container<std::variant, std::tuple<int, float, double>>::new_list v;
// v is std::variant<int, float, double>

【讨论】:

  • 好的。那行得通。看起来这是我所关注的书本身的错字。我有个问题。为什么是 template
  • 为什么模板 在主模板中只重复一次?
  • 如果你看用法,第二个参数是std::tuple&lt;int, float, double&gt;,这是一个与std::tuplestd::variant相反的类型。
猜你喜欢
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多