模板类的多个模板模板参数

时间:2017-07-25 03:42:21

标签: 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

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

1 个答案:

答案 0 :(得分:2)

这就是我认为您的意思。

#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是类型向量的元组。

第三,你可以完全摆脱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;
}