Given the following:
struct Foo { int bar() const; }; struct IsEqual : public std::unary_function<Foo*, bool> { int val; IsEqual(int v) : val(v) {} bool operator()(const Foo* elem) const { return elem->bar() == val; } };
I have a container Foo*
and I use std::find_if
and std::not1
to find out if there are any elements in the container where bar()
returns something other than the given value. The code is as follows:
// Are all elements equal to '2'? bool isAllEqual(const std::vector<Foo*> &vec) { return find_if(vec.begin(), vec.end(), std::not1(IsEqual(2))) == vec.end(); }
Fast forward to the future, and now I have another container, this time containing std::tr1::shared_ptr<Foo>
. I would like to just reuse my functor in the overloaded version of isAllEqual()
. But I can not. Foo*
and shared_ptr<Foo>
are different types. And I need to inherit from unary_function
, so I can use not1
. It would be more elegant if I could write the same functor twice.
Questions:
- Is there a way to write
IsEqual
so that it can use both raw and smart pointers? - Did I handcuff myself using
std::not1
? Should I just write IsNotEqual
instead?
Limitations:
- I cannot use anything from the boost library.
- Our compiler is not cool enough to support C ++ 0x lambdas.
c ++ functor smart-pointers adapter
Michael Kristofik
source share