简化模板参数

Simplify template arguments

本文关键字:参数      更新时间:2023-10-16

我需要根据这样的简单结构来创建模板类。它具有 AddNew的方法来插入其元组成员的新元素。

struct Type
{
  int i;
  char c;
};
template<typename ...T>
class A
{
   std::tuple<T...> ts;
   public:
     A(T&&...t):ts(std::move(t)...){}
     void AddNew(T t)
     {
        ts=std::tuple_cat(ts,t);
     }
};
int main()
{
   A<Type,Type,Type,Type> a({1,'a'},{2,'t'},{3,'c'},{4,'g'});
   Type t{5,'x'};
   a.AddNew(t);
}

问题我不想写下Type ... 4次,例如main中的4次。当我使用4 Type s或100 Type s初始化AA<Type, 100>时,我喜欢A<Type,4>之类的东西。

您可能只需要向量:

struct Type
{
  int i;
  char c;
};
template<typename T>
class A
{
   std::vector<T> data;
   public:
     template <typename ... Ts>
     A(Ts&&...ts) : data(std::forward<Ts>(ts)...){}
     void AddNew(const T& t)
     {
        data.push_back(t);
     }
};
int main()
{
   A<Type> a(Type{1,'a'}, Type{2,'t'}, Type{3,'c'}, Type{4,'g'});
   Type t{5,'x'};
   a.AddNew(t);
}

您可以部分专门为某个助手'tag'类型:

template<typename T, std::size_t N>
struct repeat{};
template<typename... T>
struct repeat_unpack{ using type = A<T...>; };
template<typename T, int N, typename... V >
struct repeat_unpack<repeat<T,N>,V...>: std::conditional_t<(N>1),
    repeat_unpack<repeat<T,N-1>,T,V...>,
    repeat_unpack<T,V...>
 >{};
template<typename T, int N>
class A<repeat<T,N>>: repeat_unpack<repeat<T,N>>::type {};
// to be used as
A<repeat<Type,3>>

上面使用继承来避免代码重复,因此您可能需要将一些成员(例如构造函数)提升到部分专业化。否则,只需使用别名

template<class T, std::size_t N>
using A_nth = typename repeat_unpack<repeat<T,N>>::type;
A_nth<Type,3>

只有一件事,鉴于您在内部使用了元组,因此简单地专门为std ::阵列并使用它,兼容元组...

ps。显然,您的AddNew()代码毫无意义,我认为这只是代码片段错字...