c++ - 如何在不递归且不将元素分解为数组的情况下扩展参数包?

标签 c++ c++11 templates c++17 variadic-templates

#include <iostream>
using namespace std;

template <class T, class... Other>
auto sum(T& first, Other... other)
{
    T mas[] = { other... };
    cout << "size: " << sizeof...(other) << endl;
    //T *f = other...;
    for (int m : mas)
        first += m;
    return first;
}

int main()
{
    int summa = 0;
    sum(summa, 1, 2, 3, 4, 5, 6, 7);
    cout << "sum: " << summa << endl;

    return 0;
}

有一小段代码输出以下内容:

size: 7
sum: 28

问题很简单,很快就能得到相同的答案: 如何逐个元素访问每个变量记账参数其他?我尝试创建一个指针,但它不断提示,总之,我不知道它在语法上看起来如何。

我会立即保留,我对如何将元素分解为数组不感兴趣,我自己知道应该如何准确地引用每个元素。

更准确地说,如何在不递归且不将元素分解为数组的情况下扩展参数包?

最佳答案

How to expand the parameter package without recursion?

自 C++17- fold expression 起,您就拥有了为了这个需求。 使用它,您的功能将很简单

template <class T, class... Other>
auto sum(T& first, const Other&... other)
{
    first = (other + ... + first);
    return first;
}

或者没有冗余变量summa可能是:

#include <type_traits>  // std::common_type_t

template <class... Other>
constexpr auto sum(const Other&... other) /* noexcept */
{
    return (other + ... + std::common_type_t<Other...>{});
}

<强> See a demo


How do I access element by element each variable accounting parameter other?

您可以将折叠表达式与 an immediately invoking lambda function 一起应用如下:

template <typename ReType, typename... Other>
auto do_something_with_args(ReType& ret, Other&&... other)
{
    ([&ret](auto /* const& */ arg) {
        // do something with each arg and ret
        ret += arg; // example
        std::cout << arg << '\n';
        }(std::forward<Other>(other)), ...);
    return ret;
}

<强> See a demo


如果您无法访问 C++17,则可以进行调整/替代方案,在以下帖子中已提到:

关于c++ - 如何在不递归且不将元素分解为数组的情况下扩展参数包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72205310/

相关文章:

c++ - 将长 64 位十进制转换为二进制

c++ - 对用于 cuda 实现的函数的 undefined reference

c++ - sqrt(x) 和 pow(x,0.5) 的区别

c++ - 如何创建n维测试数据进行聚类分析?

c++ - 以 std::string 为键的最有效关联容器?

c++ - 我不知道如何重复整个程序

c++ - 如何在不停止应用程序的情况下延迟功能

c++ - c++中成员函数模板的特化

C++ 类模板类型 std::list

c++ - 新构造的对象作为默认模板函数参数