class method in for_each
There is a class and event structure:
struct Foo
{
Foo(): name("nx"), val(9) {}
string name;
int val;
};
class Base
{
public:
Base()
{
/*array.push_back(Foo());
array.push_back(Foo());
array.push_back(Foo()); //fill array Foo
array.push_back(Foo());
array.push_back(Foo());*/
}
void Defin开发者_开发问答e(Foo* desktop)
{
cout << desktop->name << " " << desktop->val << "\n";
}
void Oblem()
{
/*for(int i = 0; i < array.size(); ++i)
{
Define(&array[i]);
}*/
for_each(array.begin(), array.end(), mem_fun_ref(&Base::Define));
}
public:
std::vector<Foo> array;
};
how can I replace the commented-out cycle on the algorithm for_each?
I now have these errors:
- error: no match for call to '(std::mem_fun1_ref_t) (Foo&)'|
- candidates are: _Ret std::mem_fun1_ref_t<_Ret, _Tp, _Arg>::operator()(_Tp&, _Arg) const [with _Ret = void, _Tp = Base, _Arg = Foo*]|
Base::Define
takes two arguments: Foo* desktop
and an implicit Base* this
. You would need to bind the current this
within Oblem
to get a function that takes only a Foo
. Also, Define
should be taking its parameter as Foo& desktop
(or better yet, if that is real code, Foo const& desktop
).
A full solution using the standard functionality within TR1 (or the Boost implementation for it) would be:
void Define(Foo const& desktop) const
{
cout << desktop.name << " " << desktop.val << "\n";
}
void Oblem() const
{
for_each(
array.begin(), array.end()
, std::bind( &Base::Define, this, _1 )
);
}
class Base
{
public:
Base() : array(5) {}
void Define(Foo &desktop)
{
cout << desktop.name << " " << desktop.val << "\n";
}
void Oblem()
{
for_each(array.begin(),array.end(),[this](Foo &f) {
Define(f);
});
// or
for_each(array.begin(),array.end(),
bind(&Base::Define,this,placeholders::_1));
}
public:
std::vector<Foo> array;
};
精彩评论