Ticket #4697: fold_join.cpp

File fold_join.cpp, 2.8 KB (added by cppljevans@…, 12 years ago)

source file

Line 
1//WARNING@2010-09-29:
2// 1) Don't try to compile this code with that from:
3/*
4http://svn.boost.org/svn/boost/sandbox/variadic_templates/
5 */
6// otherwise, you'll get a compile-time error about
7// mpl::vector0.
8//
9// 2) Only works with variadic fusion:
10/*
11http://svn.boost.org/svn/boost/sandbox/SOC/2009/fusion/
12 */
13// otherwise, you'll get compile-time error in category_of.hpp
14// about joine_view<...>& not being class, struct, or union.
15//
16//Purpose:
17// Answer question in post:
18//
19// http://article.gmane.org/gmane.comp.lib.boost.user/62386
20//
21//References:
22// [ffold]
23// http://www.boost.org/doc/libs/1_44_0/libs/fusion/doc/html
24// /fusion/algorithm/iteration/functions/fold.html
25//
26#include <boost/fusion/algorithm/iteration/fold.hpp>
27#include <boost/fusion/algorithm/transformation/join.hpp>
28#include <boost/fusion/container/vector.hpp>
29#include <boost/fusion/sequence/io.hpp>
30#include <boost/utility/result_of.hpp>
31
32#include <iostream>
33
34namespace fold_join
35{
36struct join_ftor
37/**@brief
38 * Forward decl of functor for joining 2 fusion sequences.
39 */
40;
41template<typename T,unsigned Index=0>
42struct tu
43{
44 tu(T a_t):my_t(a_t){}
45 T my_t;
46
47 friend
48 std::ostream&
49 operator<<
50 ( std::ostream& sout
51 , tu const& x
52 )
53 {
54 sout<<"tu<"<<Index<<">("<<x.my_t<<")";
55 return sout;
56 }
57};
58
59}//exit fold_join namespace
60
61namespace boost
62{
63 template
64 < typename LhSequence
65 , typename RhSequence
66 >
67struct result_of
68 < fold_join::join_ftor(LhSequence,RhSequence)
69 >
70 /**@brief
71 * As specified by table 1.37 Requirement for Parameter f
72 * in [ffold].
73 */
74: fusion::result_of::join<LhSequence, RhSequence>
75{
76};
77
78}//exit boost namespace
79
80namespace fold_join
81{
82struct join_ftor
83/**@brief
84 * modified from 'struct make_string' from [ffold].
85 */
86{
87 template<typename LhSequence, typename RhSequence>
88 typename boost::result_of<join_ftor(LhSequence,RhSequence)>::type
89 operator()(LhSequence& lhs, RhSequence& rhs)const
90 {
91 return boost::fusion::join(lhs,rhs);
92 }
93};
94}//exit fold_join namespace
95
96using namespace boost;
97using namespace fold_join;
98
99int main(void)
100{
101 typedef fusion::vector<> vec0;
102 typedef fusion::vector<tu<int,1>, tu<char,1>, tu<double,1> > t1;
103 typedef fusion::vector<tu<int,2>, tu<char,2>, tu<double,2> > t2;
104 typedef fusion::vector<tu<int,3>, tu<char,3>, tu<double,3> > t3;
105
106 vec0 state0;
107 t1 v1(100,'b',300.1);
108 t2 v2(100,'b',300.1);
109 t3 v3(100,'b',300.1);
110 std::cout<<"v1="<<v1<<"\n";
111 std::cout<<"v2="<<v2<<"\n";
112 std::cout<<"v3="<<v3<<"\n";
113 fusion::vector<t1,t2,t3> vv(v1,v2,v3);
114 join_ftor joiner;
115 auto fold_vv=fusion::fold(vv,state0,joiner);
116 std::cout
117 <<"fold(vv,state0,join_ftor())="
118 <<fold_vv
119 <<"\n";
120 return 0;
121}