I hope this acceptable forum ettiquite, I have been learning how to use the boost fusion C++ library in preparation for an interview and wanted to post what has been frustrating me for a few hours now..
The Quick Start http://www.boost.org/doc/libs/1_52_0/li ... start.html runs through some examples of how to use the library. As a relative beginner not only to boost, but also to C++, I had some difficulty getting the examples to compile. Here is my minimum working example:
Code: Select all
#include <iostream>
#include <string>
#include <typeinfo>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/algorithm/transformation/filter_if.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/fusion/container/map.hpp>
using std::cout;
using std::endl;
using std::string;
// careful if also using std::vector
using boost::fusion::vector;
using boost::fusion::for_each;
using boost::fusion::filter_if;
using boost::fusion::at_c;
using boost::is_pointer;
// required for using the '_' placeholder
using mpl_::_;
// member functions for using the map
using boost::fusion::map;
using boost::fusion::pair;
using boost::fusion::at_key;
using boost::fusion::make_pair;
// prints the elements of a container as xml
struct print_xml
{
template<class T>
void operator()(T const& x) const
{
cout
<< '<' << typeid(x).name() << '>'
<< x
<< "</" << typeid(x).name() << '>'
<< endl;
}
};
// finds the (normal) pointer elements of a Sequence and prints them as xml
template <typename Sequence>
void xml_print_pointers(Sequence const& seq)
{
for_each(filter_if<is_pointer<_> >(seq), print_xml());
}
// define some types to show how the map associates types to values
namespace fields
{
struct name;
struct age;
}
int main()
{
vector<int, char, string> stuff(1, 'x', "howdy");
int i = at_c<0>(stuff);
char ch = at_c<1>(stuff);
string s = at_c<2>(stuff);
cout << i << ", " << ch << ", " << s << endl;
for_each(stuff, print_xml());
int a = 1;
int b = 2;
int c = 3;
int d = 4;
vector<int, int*, int, int*> stuff2(a, &b, c, &d);
xml_print_pointers(stuff2);
cout << &b << endl << &d << endl;
typedef map<pair<fields::name, string>,
pair<fields::age, int> > person;
person a_person ( make_pair<fields::name>("Richie"),
make_pair<fields::age>(30));
string person_name = at_key<fields::name>(a_person);
int person_age = at_key<fields::age>(a_person);
cout << person_name << " is " << person_age << endl;
return 0;
}
Code: Select all
g++ -I/path/to/boost/libs -o fusion_example fusion_example.cpp
I hope this is helpful to anyone starting out with the very powerful boost library.1, x, howdy
<i>1</i>
<c>x</c>
<Ss>howdy</Ss>
<Pi>0x7fff41c4cf18</Pi>
<Pi>0x7fff41c4cf1c</Pi>
0x7fff41c4cf18
0x7fff41c4cf1c
Richie is 30