【问题标题】:C++: Expand array elements as parameter of a function using boost::hanaC++:使用 boost::hana 将数组元素扩展为函数的参数
【发布时间】:2016-01-10 22:44:20
【问题描述】:

我在两个月前发现了 boost::hana。看起来很强大,所以我决定看看。 从文档中我看到了这个例子:

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

相当于:

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

我想知道是否有可能(如果是的话,如何)这样写:

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

一种在编译时的“解包”,甚至:

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

【问题讨论】:

    标签: c++ boost c++14 boost-hana


    【解决方案1】:

    您的问题似乎是双重的。首先,您问题的标题询问是否可以将数组的元素扩展为函数的参数。这确实是可能的,因为std::arrayFoldable。使用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&lt;10&gt;.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) + ","; });
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2011-06-28
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多