取消引用后调用函数的函子? [英] Functor that calls a function after dereferencing?
问题描述
在 C++ 标准或 Boost 中是否有一个小函子环绕另一个函子,但在调用该函子之前取消对指针的引用?
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;
推荐答案
我不知道 C++ 标准库或 Boost 中的任何函数对象执行此操作(这并不是说没有;我不是熟悉 Boost 库中的一切 :-P).
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_;
};
使用示例:
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.
这篇关于取消引用后调用函数的函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!