With C ++ 11 we get lambdas and the ability to create functions / functors / closures on the fly, where we really need them, and not somewhere where they really don't belong. In C ++ 98/03, a good way to create local functor / closure functions would be to:
struct{ void operator()(int& item){ ++item; } }foo_functor; some_templated_func(some_args, foo_functor);
Unfortunately, you cannot use local types for templates (Visual Studio allows this with language extensions enabled). My move, although then it went like this:
struct X{ static void functor(int& item){ ++item; } }; some_templated_func(some_args, &X::functor);
The obvious problem is that you cannot save any state, since local structures / classes cannot have static members.
My next thought to solve this problem was to use combinations of std::bind1st and std::mem_fun and non-static methods and variables, but unfortunately std::mem_fun somehow throttled using std::mem_fn(&X::functor) , which again may be due to the fact that the local structure / t in the templates:
// wanted, not working solution struct X{ int n_; X(int n) : n_(n) {} void functor(int& item) const { item += n_; } }; X x(5); some_templated_func(some_args,std::bind1st(std::mem_fun(&X::functor),&x));
Failure to use VC9 and VC10 (with /Za , disabled language extensions) with the following error
error C2893: Failed to specialize function template 'std::const_mem_fun1_t<_Result,_Ty,_Arg> std::mem_fun(_Result (_Ty::* )(_Arg) const)' With the following template arguments: 'void' 'main::X' 'int &'
Or under gcc 4.3.4 with this error
error: no matching function for call to 'mem_fun(void (main()::X::*)(int&))'
Oddly enough, the VC9 / VC10 is still suffocating in the above example, even with language extensions:
error C2535: 'void std::binder1st<_Fn2>::operator ()(int &) const' : member function already defined or declared
So, as far as possible, the functionality stated in the title? Or am I making a mistake in the last example of how I use std::bind1st or std::mem_fun ?