Functor that calls a function after dereferencing?

夙愿已清 提交于 2019-12-23 12:55:47

问题


Is there a small functor in the C++ standard or in Boost that wraps around another functor, but dereferences a pointer before it calls that functor?

I'm thinking of something like this:

template<class F>
struct DerefCmp {
  template<class T>
  bool operator()(T* v) const {
    return F(*v);
  }
};

I'd use it in a container of pointers, for example, where I want to compare by value:

std::set<int*, DerefCmp< std::equal<int> > > s;

回答1:


I am not aware of any function object in the C++ Standard Library or in Boost that does this (that's not to say there isn't one; I am not familiar with everything in the Boost libraries :-P).

However, writing your own is rather straightforward. Consider the following:

template <typename Predicate>
class indirect_binary_predicate
{
public:
    indirect_binary_predicate(const Predicate& pred = Predicate()) 
        : pred_(pred) 
    {
    }

    template <typename Argument0, typename Argument1>
    bool operator()(Argument0 arg0, Argument1 arg1) const 
    { 
        return pred_(*arg0, *arg1); 
    }

private:
    Predicate pred_;
};

Usage example:

std::set<int*, indirect_binary_predicate<std::equal_to<int> > > s;

Note that it is ill-advised to have a container of raw pointers if the pointers are to dynamically allocated objects and the container has ownership of the pointed-to objects; it isn't exception-safe to do this. That said, this predicate adapter should work just as well for smart pointers, iterators, or any other type that supports dereferencing.




回答2:


You may look at the boost pointer containers. They can be used for this purpose with the standard functors: Boost.PointerContainer



来源:https://stackoverflow.com/questions/6269313/functor-that-calls-a-function-after-dereferencing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!