Rokiのチラ裏

学生による学習のログ

tupleに対してfor_each

ここ数年のC++の言語仕様の拡張や発展はとても活発だ。そんな中、筆者が2~3年近くC++に触れていなかったのは、少し失敗したなと、個人的に日々感じる。
tupleについても、同じ動作を全ての各要素に対して実行する方法が、その2~3年の間には既にあった。

#include<tuple>
#include<sstream>
#include<boost/fusion/adapted/std_tuple.hpp>
#include<boost/fusion/include/for_each.hpp>
#include<iostream>

template<char _delimitor=' ',class ...Args>
std::string make_string(const std::tuple<Args...>& tp)
{
    std::ostringstream os;
    boost::fusion::for_each(tp,[&os](auto x){os<<x<<_delimitor;});
    os.str().pop_back();
    return os.str();
}

int main()
{
    std::tuple<int,int,int> t{1,2,3};
    std::cout<<make_string(t)<<std::endl;
}

boost::fusion、とても便利だ。