Re: class member function binding
On Jul 17, 11:01 am, Ulrich Eckhardt <eckha...@satorlaser.com> wrote:
zade wrote:
struct ConstM
{
void test() const
{
std::cout << "test const" << std::endl;
}
void test()
{
std::cout << "test" << std::endl;
}
};
int main()
{
ConstM c;
std::for_each(&c,&c+1,boost::bind(&ConstM::test,_1));
}
so which one member function does &ConstM::test points to , the const
or the none const one?
Actually I'm surprised that this compiles, as there is no way for the
compiler to determine which of the two overloads you wanted in the call to
bind(). Unless it is clear from the existing context which one is meant,
you need a static_cast to establish that context and thus allow the
compiler to determine the correct overload.
A C++ compiler determines which test() member function to call (the
const or non-const version) depending on the constness of the ConstM
object itself. That is, a const ConstM object would call
ConstM::test() const, whereas a non-const ConstM object would call
ConstM::test(). Note that a static_cast<> could not be used to specify
which test() method to call - because a static_cast may not change the
const-ness of an object.
So, the question is whether std::for_each() should pass a const or non-
const element to bind() - its function object. Well, there has been
some uncertainty on this issue in the past, but the consensus now
appears to be that std::for_each() should pass a reference to a non-
const element. Because - even though for_each()'s function object
should not modify the container (that is, it should not invalidate any
of the container's iterators), there is no reason why the function
object should not be allowed to modify the elements themselves.
Certainly, std::for_each() is great more useful when it passes a non-
const object to its function object. So in this case, Visual C++'s
implementation of std::for_each() - appears to be the most up-to-date.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]