使用范围作为参数包
Using a range as a parameter pack
我有一个功能
#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
有什么方法可以转换参数包中的范围吗?在此先感谢任何人。
编译时不能使用运行时值。
向量大小是运行时值,包大小是编译时间。
但是,如果您在编译时知道大小,您可能会这样做:
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));
或
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
}
我有一个功能
#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
有什么方法可以转换参数包中的范围吗?在此先感谢任何人。
编译时不能使用运行时值。
向量大小是运行时值,包大小是编译时间。
但是,如果您在编译时知道大小,您可能会这样做:
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));
或
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
}