使用范围作为参数包

问题描述

我有一个功能

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

如果我也有一个向量

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

有没有办法将包含我的数字的范围作为参数包传递给函数? 我想要的结构类似于

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

其中 SomethingMagic 将范围转换为包以获取表单中的输出

1 2 3 4 5

有没有办法转换参数包中的范围?提前感谢任何人。

解决方法

您不能将运行时值用于编译时间一。

vector size 是运行时值,pack 的大小是编译时间。

但是,如果您在编译时知道大小,您可能会执行以下操作:

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

然后

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

Demo

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
}