作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
鉴于以下情况:
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;
}
};
我有一个容器 Foo*
我用std::find_if
和 std::not1
找出容器中是否有任何元素 bar()
返回与给定值不同的东西。代码如下所示:
// 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();
}
快进到 future ,我现在有了一个不同的容器,这次包含 std::tr1::shared_ptr<Foo>
.我很乐意在 isAllEqual()
的重载版本中简单地重新使用我的仿函数.但我不能。 Foo*
和 shared_ptr<Foo>
是不同的类型。我需要继承 unary_function
所以我可以使用 not1
.如果我可以避免两次编写相同的仿函数,那就更优雅了。
问题:
IsEqual
所以它可以同时使用原始指针和智能指针?std::not1
给自己戴上手铐了吗? ?我应该只写 IsNotEqual
吗?相反?限制:
最佳答案
怎么样:
template<typename T>
struct IsEqual : public std::unary_function<const T&, bool>
{
int val;
IsEqual(int v) : val(v) {}
bool operator()(const T& elem) const
{
return elem->bar() == val;
}
};
template<typename T>
IsEqual<T> DeduceEqualityComparer(int v, T) { return IsEqual<T>(v); }
// Are all elements equal to '2'?
template<typename TContainer>
bool isAllEqual(const TContainer& coll)
{
using std::begin; // in C++0x, or else write this really simple function yourself
using std::end;
if (begin(coll) == end(coll)) return true;
return find_if(begin(coll), end(coll), std::not1(DeduceEqualityComparer(2, *begin(coll)))) == end(coll);
}
关于c++ - 我可以编写一个接受原始指针和智能指针的 C++ 仿函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4433155/
我是一名优秀的程序员,十分优秀!