首页 > 解决方案 > 如何构造带有常规函数参数的 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);
    
}

编辑:这不会编译为它的假代码,但是类似的函数可以用数据类型的数据填充向量吗?

标签: c++

解决方案


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;
}

推荐阅读