Robert Jones wrote:
Hi Folks,
Can anyone tell me why this is wrong? My intention is to call A::f()
for each A constructed
on-the-fly from the elements of v.
Thanks, Rob.
Hi Rob -
Since I'm promoting phoenix these days (o;
Here is one way you could do it --------------------
#include <iostream>
#include <vector>
#include
struct A
{
A( int i ) : i_( i ) {}
void f(){ std::cout << i_ << std::endl; }
int i_;
};
int main()
{
using namespace boost::phoenix;
using namespace boost::phoenix::arg_names;
using namespace boost::phoenix::local_names;
std::vector< int > vec;
// fill the vector with something
for( int i=0; i < 10; ++i )
{
vec.push_back( i );
}
// create an A for each vector entry
std::for_each( vec.begin(), vec.end(),
let( _a = construct<A>(arg1) )
[
bind( &A::f, _a )
]
);
return 0;
}
------------------------------------------------
And now say we want to do something a little more interesting ... like
store the newly constructed object in a vector also.
#include <iostream>
#include <vector>
#include
struct A
{
A( int i ) : i_( i ) {}
void f(){ std::cout << i_ << std::endl; }
int i_;
};
int main()
{
using namespace boost::phoenix;
using namespace boost::phoenix::arg_names;
using namespace boost::phoenix::local_names;
std::vector< int > vec;
std::vector< A > a_vec;
// fill the vector with something
for( int i=0; i < 10; ++i )
{
vec.push_back( i );
}
// create an A for each vector entry, call f()
// on the object and store it in a vector
std::for_each( vec.begin(), vec.end(),
let( _a = construct<A>(arg1) )
[
bind( &A::f, _a ),
push_back( ref(a_vec), _a )
]
);
// print out our vector of A's using a phoenix bind
// to a member variable
std::for_each( a_vec.begin(), a_vec.end(),
( std::cout << bind( &A::i_, arg1) << " " ) );
return 0;
}
------------------------------------------------
Write the "push_back" for bind/lambda ... you will see why phoenix is so
much nicer to look at.
michael
--
----------------------------------
Michael Caisse
Object Modeling Designs
www.objectmodelingdesigns.com