C ++:使用boost :: hana展开数组元素作为函数的参数 [英] C++: Expand array elements as parameter of a function using boost::hana
问题描述
我发现两个月前boost :: hana。看起来非常强大,所以我决定看看。
从文档中我看到这个例子:
I discovered two months ago boost::hana. Seems very powerfull so I decided to take a look. From the documentation I saw this examples:
std::string s;
hana::int_c<10>.times([&]{ s += "x"; });
等效于:
s += "x"; s += "x"; ... s += "x"; // 10 times
我想知道是否可能写smthg像:
I'd like to know if it is possible (and if yes how) to write smthg like:
std::string s;
std::array<int, 10> xs = {1, 3, 5, ...};
hana::int_c<10>.times([&](int i){ s += std::to_string(xs[i]) + ","; });
在编译时会解压缩,甚至:
a sort of "unpacking" at compile time, or even:
myfunction( hana::unpack<...>( xs ) );
推荐答案
首先,你的问题的标题询问是否可以扩展数组的元素作为函数的参数。确实有可能,因为 std :: array
是 可折叠
。可以使用 hana :: unpack
:
Your question seems twofold. First, the title of your question asks whether it is possible to expand the elements of an array as the parameters of a function. It is indeed possible, since std::array
is Foldable
. It suffices to use hana::unpack
:
#include <boost/hana/ext/std/array.hpp>
#include <boost/hana/unpack.hpp>
#include <array>
namespace hana = boost::hana;
struct myfunction {
template <typename ...T>
void operator()(T ...i) const {
// whatever
}
};
int main() {
std::array<int, 10> xs = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}};
hana::unpack(xs, myfunction{});
}
其次,你问是否可以做类似
Secondly, you ask whether it is possible to do something like
std::string s;
std::array<int, 10> xs = {1, 3, 5, ...};
hana::int_c<10>.times([&](int i){ s += std::to_string(xs[i]) + ","; });
这个问题的答案是使用 hana :: int_c< 10> ;. times.with_index
:
The answer to this is to use hana::int_c<10>.times.with_index
:
hana::int_c<10>.times.with_index([&](int i) { s += std::to_string(xs[i]) + ","; });
同样,您也可以使用 hana :: for_each
:
hana::for_each(xs, [&](int x) { s += std::to_string(x) + ","; });
这篇关于C ++:使用boost :: hana展开数组元素作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!