gpt4 book ai didi

c++ - 我可以编写一个接受原始指针和智能指针的 C++ 仿函数吗?

转载 作者:可可西里 更新时间:2023-11-01 17:35:57 26 4
gpt4 key购买 nike

鉴于以下情况:

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_ifstd::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 吗?相反?

限制:

  1. 我不能使用 boost 库中的任何东西。
  2. 我们的编译器不够酷,无法支持 C++0x lambda。

最佳答案

怎么样:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com