Home > Mobile >  How to write an overload function for std::array that calls a variadic function?
How to write an overload function for std::array that calls a variadic function?

Time:07-14

I have the following variadic function:

template <typename... Args>
CustomType<Args...> method(const Args& args...);

which works fine when I just do e.g.

method(1.0f, 2.0f, 3.0f);

However I also want to write an overload for std::array<T, N>:

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr);

Reading this post I figured I would use the following helper functions:

template <typename T, std::size_t N, typename VariadicFunc, uint32_t... I>
auto methodApply(const std::array<T, N>& arr, VariadicFunc func, std::index_sequence<I...>)
{
    return func(arr[I]...);
}

template <typename T, std::size_t N, typename VariadicFunc, typename Indices = std::make_index_sequence<N>>
auto methodArr(const std::array<T, N>& arr, VariadicFunc func)
{
    return methodApply(arr, func, Indices());
}

and then do

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr)
{
   methodArr(arr, /* what to pass here? */);
}

Note: the reason why I would like to template on func is because I want these helper functions to be generic so that I may use them for other variadic functions, not just method().

Only I'm not sure what pass as the second argument - I was thinking of a lambda function that would make a call to the original function method(const Args& args...) but it's unclear to me how to do this.

EDIT: Restricted to C 14.

CodePudding user response:

You can wrap it in a lambda and let the compiler deduce the type for you

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr)
{
   return methodArr(arr, [](const auto&... args) { return method(args...); });
}

Demo

In C 17, methodApply can be replaced with std::apply

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr) {
  return std::apply(
    [](const auto&... args) { return method(args...); }, arr);
}
  • Related