Using std::bind2nd with my own functions

Started by
3 comments, last by deavik 17 years, 9 months ago
Just for fun I was trying to write a simple tree class, and since I didn't code any iterators for it, I have a member find_node function for which I need std::binder2nd's functionality. The function is basically like this: bool find_node(bool (*func)(const node_attribute&), node_ptr& out_ptr); Obviously bind2nd can only give me new function objects, so I tried bool find_node(std::unary_function< node_attribute, bool > func, node_ptr& out_ptr); but in the latter case how do I call the function denoted by the function object? Or is there another way? Please tell me if mre info is required, also. Thanks! [smile]
Advertisement
std::binary/unary_function is used to make functional objects adaptable functions. They only contain nested type aliases, there are not polymorphic types either.

This is what you want:

template < typename Predicate >bool find_node(Predicate cmp, node_ptr& out_ptr);


Now you can use it with any C++ callable entity, free-functions, static member functions, bound non-static member functions, functional obects, etc, etc.
Thanks. I would never have imagined it would be that simple [smile].
When you need a hint like this about how to work with standard library stuff, usually you can get it from looking at how standard library pieces work with each other. :) (See std::for_each for example.)
Quote:Original post by Zahlman
When you need a hint like this about how to work with standard library stuff, usually you can get it from looking at how standard library pieces work with each other. :) (See std::for_each for example.)

I actually did, I had looked at find_if's definition in stl_algo.h and sure enough it had a template< typename _Predicate >. As I wrote before, I didn't imagine you could template any callable entity so I thought there must be some black magic there [smile]. Pity I didn't even try it out though; but anyway thanks for the tips, guys.

This topic is closed to new replies.

Advertisement