C++:使用 boost::hana 扩展数组元素作为函数的参数

C++: Expand array elements as parameter of a function using boost::hana

两个月前我发现了boost::hana。似乎非常强大,所以我决定看一看。 从文档中我看到了这个例子:

std::string s;
hana::int_c<10>.times([&]{ s += "x"; });

相当于:

s += "x"; s += "x"; ... s += "x"; // 10 times

我想知道是否可以(如果可以的话)像这样写 smthg:

std::string s;
std::array<int, 10> xs = {1, 3, 5, ...};
hana::int_c<10>.times([&](int i){ s += std::to_string(xs[i]) + ","; });

编译时的一种"unpacking",甚至:

myfunction( hana::unpack<...>( xs ) );

你的问题似乎是双重的。首先,你的问题的标题问是否可以扩展数组的元素作为函数的参数。确实有可能,因为std::array is Foldable。使用 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{});
}

其次,你问是否可以做类似的事情

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:

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) + ","; });