Search code examples
c++variadic-functions

Using a range as a parameter pack


I have a function

#include <iostream>
#include <iterator>
#include <vector>

template <typename T, typename P...> Function (T&& Sth, P&&... SthElse) {
    //Perform operations on all arguments. For example:
    std::cout << Sth << " ";
    (std::cout << ... << SthElse);
    std::cout <<"\n"; 
}

If I also have a vector

int main () {
    std::vector<int> V {1, 2, 3, 4, 5};
}

is there some way to pass the range containing my numbers to the function as a parameter pack? My desired structure would be something like

    Function(SomethingMagic(V.begin(), V.end());

where SomethingMagic turns the range into a pack to get an output in the form

1 2 3 4 5

Is there any way to convert the range in a parameter pack? Thanks in advance to anyone.


Solution

  • You cannot use runtime value for compile time one.

    vector size is a runtime value, size of pack is compile time.

    But, if you know size at compile time, you might do something like:

    template <typename C, std::size_t ... Is>
    auto to_tuple_impl(C&& c, std::index_sequence<Is...>)
    {
        return std::tie(c[Is]...);
    }
    
    template <std::size_t N, typename C>
    auto to_tuple(C&& c)
    {
        return to_tuple_impl(std::forward<C>(c), std::make_index_sequence<N>());
    }
    

    and then

    std::apply([](auto...args){Function(args...); }, to_tuple<5>(v));
    

    Demo

    or

    switch (v.size())
    {
        case 5: return std::apply([](auto...args){Function(args...); }, to_tuple<5>(v));
        case 42: return std::apply([](auto...args){Function(args...); }, to_tuple<42>(v));
        // ...
        default: return; // Nothing
    }