使用数组作为参数在 C++ 中调用可变参数函数

Call variadic function in C++ with array as arguments

假设我有一个像这样的简单可变函数:

template <typename... A>
void func(A... args)
{
    //Do stuff
}

而且我需要另一个函数来调用数组中的参数,比方说:

int arg[3] = {1,2,3};

调用函数

func(1,2,3);

是否可以在不修改模板函数的情况下执行此操作?

你可以写 apply ,它引用一个数组和仿函数来调用解压后的数组(你可能想添加完美转发等):

template <typename F, typename T, std::size_t N, std::size_t... Idx>
decltype(auto) apply_impl (F f, T (&t)[N], std::index_sequence<Idx...>) {
    return f(t[Idx]...);
}

template <typename F, typename T, std::size_t N>
decltype(auto) apply (F f, T (&t)[N]) {
    return apply_impl(f, t, std::make_index_sequence<N>{});   
}

然后这样调用,如果foo是一个函子class:

apply(foo{}, a);

如果 foo 只是像您的示例中那样的普通模板函数,您可以将其包装在 lambda 中:

apply([](auto...xs){foo(std::forward<decltype(xs)>(xs)...);}, a);

Live Demo