c++ - 如何构造带有常规函数参数的 C++ 可变参数函数
问题描述
template<class... Args>
void print(Args... args)
{
(std::cout << ... << args) << "\n";
}
void test(){
print(1, ':', " Hello", 2 , ',', " ", "World!");
}
以上适用于文本
template<class... Args>
void add(int & i, Args... args)
{
i += args...;
}
void test(){
int i;
add(i, 1, 2, 3);
}
编辑:这不会编译为它的假代码,但是类似的函数可以用数据类型的数据填充向量吗?
解决方案
Two ways of going over the args (in this case all of the same type), if this is not enough for you consider looking into type lists. How to use typelists
// With recursion and if constexpr
template<typename arg_t, typename... args_t>
constexpr auto sum_recurse(arg_t n, args_t&&... ns)
{
if constexpr (sizeof...(args_t) == 0)
{
return n;
}
else
{
return n + sum_recurse(ns...);
}
}
// or in this case for operations you can use fold expressions
template<typename... args_t>
constexpr auto sum_fold(args_t&&... args)
{
return (args + ...);
};
int main()
{
static_assert(sum_recurse(1, 2, 3) == 6);
static_assert(sum_fold(1, 2, 3) == 6);
return 0;
}
推荐阅读
- java - 模型类的圈复杂度
- matlab - 如何在 Matlab 中查看给定平面上的东西?
- ios - 汇编代码中的 iOS 12 错误 swift_getAssociatedTypeWitnessSlowImpl EXC_BAD_ACCESS
- javascript - 当对象键存在于javascript中另一个对象的数组中时,重构对象数据
- java - 如何创建一个不覆盖现有对象的新实例?
- ios - 如何将特定元素从数组传递到另一个视图或函数?迅速
- amazon-web-services - Amazon Cloudwatch Logs,解析函数的日期时间结果
- android - 如何设置通知渠道?
- python - 如何在不影响图像其余部分的情况下删除图像中的外圈?
- c++ - 连接一个 UDP 套接字,但仍然接收来自其他来源的数据报