可以比较两个函子的相等性吗? [英] Can two functors be compared for equality?
问题描述
是否有一种方法可以接收两个仿函数作为参数,以找出它们是否指向同一函数?具体来说,具有这样的结构:
Is there a way for a method, which receives two functors as arguments, to find out if they are pointing to the same function? Specifically, having a struct like this:
struct FSMAction {
void action1() const { std::cout << "Action1 called." << std::endl; }
void action2() const { std::cout << "Action2 called." << std::endl; }
void action3() const { std::cout << "Action3 called." << std::endl; }
private:
// Maybe some object-specific stuff.
};
这样的方法:
bool actionsEqual(
const std::function<void(const FSMAction&)>& action1,
const std::function<void(const FSMAction&)>& action2)
{
// Some code.
}
是否有某些代码会返回 true
仅适用于:
Is there "some code" that will return true
only for:
actionsEqual(&FSMAction::action1, &FSMAction::action1)
但不适用于:
actionsEqual(&FSMAction::action1, &FSMAction::action2)
也许这个问题没有任何意义(第一个线索可能是互联网上似乎没有关于它的一切……)。如果是这样,您能否给出一个提示,为什么,以及是否有方法可以完成相似的事情? (基本上,我希望在上述意义上有一组仅包含唯一项目的回调。)
Maybe this question doesn't make any sense (first clue would be that there seems to be nothing on the internet about it...). If so, could you give a hint, why, and if there are ways to accomplish something "similar"? (Basically, I'd like to have a set of callbacks with only "unique" items in the above-outlined sense.)
推荐答案
原始函数最终是一个指针。您可以将其挖出() std :: function
与 std :: function :: target
,然后它只是 void的比较*
。
A raw function is eventually a pointer. You can dig it out of std::function
with std::function::target
and then it's simply a comparison of void*
.
这篇关于可以比较两个函子的相等性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!