首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模板类的多模板模板参数

模板类的多模板模板参数
EN

Stack Overflow用户
提问于 2017-07-25 11:42:21
回答 1查看 68关注 0票数 3

可以将两个模板类传递到一个模板类中吗?

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

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

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

代码语言:javascript
复制
#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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-25 12:52:12

我想这就是你的意思。

代码语言:javascript
复制
#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。除非它正在做这段代码中没有的功能。

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45293532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档