ekinmur ekinmur - 4 months ago 27
C++ Question

why does mem_fn() complain about attempt to use a deleted function?

I have the following snippet :

struct Foo {
Foo(int num):num_(num){}
void print_add(int i) const { std::cout << num_+i << '\n'; }
int num_;

int main() {
std::vector<Foo*> vpf{ new Foo(3), new Foo(4), new Foo(5) };

auto pfa = std::mem_fn(&Foo::print_add);
int i = 42;

//std::for_each(vpf.begin(), vpf.end(), [&i](const auto& val){val -> print_add(i);});
std::for_each(vpf.begin(), vpf.end(), pfa(&i));

return 0;

Commented code that uses a lambda expression actually works as I expect printing 45, 46, 47. The uncommented code with
that uses
causes a compilation error
attempt to use a deleted function

Can someone explain why and how I can properly use
in this scenario?


std::mem_fn creates a functor that takes a reference or pointer to the type as the first parameter, and forwards the rest of its parameters to the actual function.

When passing it to an algorithm, you're not supposed to call it's () operator (you didn't do this for your lambda example). Your problem is that you also want to provide an argument to your function, and this simply isn't possible with just mem_fn. You can do this with std::bind or a lambda, though.

std::for_each(vpf.begin(), vpf.end(), std::bind(pfa, std::placeholders::_1, i));


std::for_each(vpf.begin(), vpf.end(), [&i,&pfa](const auto& val){ pfa(val, i); });

That being said, I think it's best to go with the lambda from your example. bind is controvesial, and if you're using a lambda anyway, what's the point of adding mem_fn to it?