扩展模板参数包以声明类成员

时间:2021-03-20 20:06:44

标签: c++

首先,我有一个模板类:

template <typename T>
class Component;

然后我想创建一个类,该类可以包含任意一组 Component<T> 作为成员,例如对于N=2

template <typename T, typename U>
class Aggregate
{
private:
  Component<T>* m_comp1;
  Component<U>* m_comp2;
};

乍一看,使用可变参数模板似乎很自然。

template <typename... Comps>
class Aggregate
{
// what should go here for me to get Component<Comp1>, Component<Comp2>, ...?
};

但是,我无法编写基本上允许我从 T, U, ... -> C<T>, C<U>, ... 开始的代码。目前,我通过为每个 N=1,2,3,4,... 案例创建部分特化来实现这一点,但这会产生大量重复的样板代码(我想避免编写 Aggregate 类来接受模板参数直接作为 <Comp<T>,Comp<U>,...>)。有没有办法实现上述目标?感谢您提前提供任何反馈/帮助。

2 个答案:

答案 0 :(得分:2)

尝试使用元组:

template <typename... Comps>
using Aggregate = std::tuple<Component<Comps>*...>;

答案 1 :(得分:0)

没有简单的解决方案。使用std::tuple。否则你需要自己重新实现它,这不是微不足道的。

相关问题