加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:01:05 所属栏目:百科 来源:网络整理
导读:我两个月前发现了boost :: hana.看起来非常强大所以我决定看一看. 从文档中我看到了这个例子: std::string s;hana::int_c10.times([]{ s += "x"; }); 这相当于: s += "x"; s += "x"; ... s += "x"; // 10 times 我想知道是否有可能(如果是的话)写smthg: s
我两个月前发现了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]) + ","; });

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

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

解决方法

你的问题似乎有两个方面.首先,您的问题的标题询问是否可以将数组的元素扩展为函数的参数.确实可能,因为 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,4,6,7,8,9,10}};
    hana::unpack(xs,myfunction{});
}

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

std::string s;
std::array<int,"; });

答案是使用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) + ","; });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读