c++ - 模板类的多个模板模板参数

标签 c++ templates metaprogramming variadic-templates template-templates

是否可以将两个模板类传递给一个模板类?

我希望创建一个包含两个不同 std::tuple<std::vector<>> 的类.

我开始怀疑我想要实现的目标无法完成,但我找不到任何相反的说法。

下面是我正在使用的代码:

#include <iostream>
#include <vector>
#include <tuple>

template<typename... Ts>
struct Typelist
{
  static constexpr std::size_t size { sizeof...(Ts) };   
};

template<class, class> class World;

template<template<typename... Arg1> class T1, template<typename... Arg2> class T2>
class World<Typelist, Typelist>
{

private:
  std::tuple<std::vector<T1>...> m1;
  std::tuple<std::vector<T2>...> m2;
};


int main() {
    // your code goes here
    using TL1 = Typelist<int, char, double>;
    using TL2 = Typelist<float, unsigned int, bool>;

    World<TL1, TL2> w2;
    return 0;
}

Live Example

这可能吗?如果可能,我做错了什么? 如果没有,是否有可能的替代方案?

最佳答案

这就是我想你可能的意思。

#include <iostream>
#include <vector>
#include <tuple>

template<typename... Ts>
struct Typelist
{
  static constexpr std::size_t size { sizeof...(Ts) };   
};

template <class, class>
class World;

template <typename... Arg1, typename... Arg2>
class World<Typelist<Arg1...>, Typelist<Arg2...>>
{

  private:
    std::tuple<std::vector<Arg1>...> m1;
    std::tuple<std::vector<Arg2>...> m2;
};


int main() {
  using TL1 = Typelist<int, char, double>;
  using TL2 = Typelist<float, unsigned int, bool>;

  World<TL1, TL2> w2;
  return 0;
}

所做的更改:

首先,模板特化改为两个裸参数包,这是可行的,因为参数包是由模板匹配引擎根据Typelist的类型填充的,所以是明确的.您不能使用您之前使用的规范,因为那样您只能访问 T1T2,您无权访问内部参数包参数的名称。

其次,我更改了 World 的数据成员的定义方式,因此 m1m2 是类型 vector 的元组。

第三,你可以完全摆脱Typelist,直接使用tuple。除非它正在执行此代码中未包含的内容。

#include <iostream>
#include <vector>
#include <tuple>

template <class, class>
class World;

template <typename... Arg1, typename... Arg2>
class World<std::tuple<Arg1...>, std::tuple<Arg2...>>
{

  private:
    std::tuple<std::vector<Arg1>...> m1;
    std::tuple<std::vector<Arg2>...> m2;
};


int main() {
  using TL1 = std::tuple<int, char, double>;
  using TL2 = std::tuple<float, unsigned int, bool>;

  World<TL1, TL2> w2;
  return 0;
}

关于c++ - 模板类的多个模板模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293532/

相关文章:

Ruby元编程,定义多个 "inherited"函数

c++ - 删除单向链表的列表

c++ - 无法重载虚函数

python - 模板标签包含预期在 Django 框架中找到的文件在哪里

c++ - 如何在构造函数中为不同的类使用模板化类

c++ - 循环展开和元编程(TMP)?

javascript - 如何在javascript中以字符串形式访问对象属性

c++ - 3DS 模型加载 - 树/层次结构

c++ - 为什么建议在删除后将指针设置为null?

c++ - 不能在派生模板类中使用 struct 吗?