Re: what is wrong with this code?
Martin Eisenberg wrote:
SG wrote:
...which makes me wonder why nobody proposed a pointer type such
an expression could decay to for C++0x. Such a pointer type
should be class-agnostic and much easier to implement than
member function pointers [1].
Instead, we have to use mem_fun and bind1st. Unfortunately, the
resulting type of bind1st(mem_fun(.),.) depends on the member
function's class type and requires the use of templates and/or
type erasure.
How about employing a lambda expression? Wouldn't that be passable by
function pointer?
No. A lambda expression creates an rvalue of a unique and anonymous
type which has an overloaded function call operator. Whether you use
std::bind or a lambda expression doesn't make a big difference.
class B {
public:
void foo(int);
};
template<typename Func>
void bar1(Func f) {
f(23);
}
void bar2(function<void(int)> f) {
f(23);
}
int main() {
B b;
B* pb = &b;
bar1(bind(&B::foo,pb,_1));
bar2(bind(&B::foo,pb,_1));
bar1([pb](int i){pb->foo(i);});
bar2([pb](int i){pb->foo(i);});
}
bar1 is a template. Instead of calling B::foo directly it invokes a
proxy which forwards the call to B::foo. For every class you get a
different specialization of bar1. (one "indirection")
bar2 is not a template. It uses a polymorphic function object (type
erasure). bar2 calls function<void(int)>::operator() which calls a
virtual function which calls another operator() which finally calls
B::foo. (three "indirections")
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]