简化模板参数
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初始化A
或A<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()
代码毫无意义,我认为这只是代码片段错字...
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用