说要存储以下内容:
typedef std::function<void(int)> MyFunctionDecl;
..在一个集合中:
typedef std::vector<MyFunctionDecl> FunctionVector;
FunctionVector v;
这是可能的,但如果我想find 使用 std::find
:
FunctionVector::const_iterator cit = std::find(v.begin(), v.end(), myFunctionDecl);
.. 由于 ==
运算符,我们得到一个错误。
正如在上一个问题中向我建议的那样,这可以通过将函数声明封装在另一个类中来解决,该类提供 ==
运算符:
class Wrapper
{
private:
MyFunctionDecl m_Func;
public:
// ctor omitted for brevity
bool operator == (const Wrapper& _rhs)
{
// are they equal?
}; // eo ==
}; // eo class Wrapper
所以我想做的是以某种方式为“MyFunctionDecl”生成一个哈希,以便我可以正确实现 ==
运算符。我可以有某种唯一标识符,并要求调用者为委托(delegate)提供唯一标识符,但这似乎有点麻烦并且容易出错。
有没有办法可以做到这一点?这样相同的函数将返回相同的 ID 用于比较目的吗?到目前为止,解决它的唯一方法是放弃使用 std::function
的概念,转而使用支持比较的快速委托(delegate)。但后来我失去了使用 lambdas 的能力。
任何帮助表示赞赏!
编辑
鉴于下面的答案,这就是我想出的......我可能错过的任何警告?我现在正在逐步完成它:
class MORSE_API Event : boost::noncopyable
{
public:
typedef std::function<void(const EventArgs&)> DelegateType;
typedef boost::shared_ptr<DelegateType> DelegateDecl;
private:
typedef std::set<DelegateDecl> DelegateSet;
typedef DelegateSet::const_iterator DelegateSet_cit;
DelegateSet m_Delegates;
public:
Event()
{
}; // eo ctor
Event(Event&& _rhs) : m_Delegates(std::move(_rhs.m_Delegates))
{
}; // eo mtor
~Event()
{
}; // eo dtor
// methods
void invoke(const EventArgs& _args)
{
std::for_each(m_Delegates.begin(),
m_Delegates.end(),
[&_args](const DelegateDecl& _decl) { (*_decl)(_args); });
}; // eo invoke
DelegateDecl addListener(DelegateType f)
{
DelegateDecl ret(new DelegateType(f));
m_Delegates.insert(ret);
return ret;
}; // eo addListener
void removeListener(const DelegateDecl _decl)
{
DelegateSet_cit cit(m_Delegates.find(_decl));
if(cit != m_Delegates.end())
m_Delegates.erase(cit);
}; // eo removeListener
}; // eo class Event
最佳答案
你看过Boost Signals ?它可能已经在做你想做的事了。
无论如何,包装 function
的一种简单方法是使用 shared_ptr
。如果你这样做了
typedef std::shared_ptr<std::function<void(int)> > MyFunctionDecl;
并确保函数在创建时立即包装在 shared_ptr
中(以便指针是唯一的),可以测试指针是否相等,以便 std::find
可以工作。
例如,您可以使用像
这样的工厂函数来执行此操作template <class Functor>
MyFunctionDecl createDelegate(Functor f) {
return MyFunctionDecl(new std::function<void(int)>(f));
}
这样,您在创建委托(delegate)时为函数(其指针)提供唯一标识。
顺便说一句,我会使用 std::set
而不是 std::vector
,作为 find
和 删除
是对数而不是线性的。
关于c++ - std::function<> 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4584685/