Re: passing function object pointer to for_each argument
Hi
hongseok.yoon@gmail.com schreef:
[class test_b derived from test_a and overriding _test]
int main()
{
test_a* a = new test_a;
test_a* b = new test_b;
vector<int> v;
v.push_back(1);
for_each(v.begin(), v.end(), *a);
for_each(v.begin(), v.end(), *b);
delete a;
delete b;
return 0;
}
Result :
test_a::_test()
test_a::_test()
------------------------------------------------
Why the result is not...
test_a::_test()
test_b::_test()
???
tell me why and how can I fix it?
Slicing. The problem is that template argument deduction chooses
"test_a" as the type of the second parameter. So for_each will only ever
see a test_a object, which is a copy of the test_a sub-object of *b.
To avoid this, I see two options:
1. explicitly instantiate for_each with a reference parameter:
for_each<vector<int>::iterator, test_a&>(v.begin(), v.end(), *b);
But I'm not completely certain if this is guaranteed to work.
2. use a combination of boost::function and boost::ref:
for_each(v.begin(), v.end(),
boost::function<void(int)>(boost::ref(*b)));
Markus
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]