簡體   English   中英

如何比較 std::function 對象?

[英]How can I compare std::function objects?

我有一個std::function對象的向量,定義如下:

std::vector<std::function<void()>> funcs = { myFunc1, myFunc2, myFunc3 };
//The functions are defined like this:
//void myFunc1() { ... }

我正在嘗試在此數組中搜索特定的 function。 我的第一次嘗試是使用std::find function,如下所示:

auto iter = std::find(funcs.begin(), funcs.end(), myFunc2);
//CS2679: binary '==': no operator found which takes a right-hand operator of type '_Ty (__cdecl &)' or there is no acceptable conversion

我學到了std::function::operator==()不比較相等的艱難方法,除非 function 對象為空(顯然不是這種情況)。 所以我嘗試使用std::find_if來使用std::function::target()方法:

auto iter = std::find_if(funcs.begin(), funcs.end(), [](const std::function<void()>& f)
    {
        if (*f.target<void()>() == myFunc2)
        //using or not using that '*' before f in the condition makes no difference in the error
            return true;
        return false;
    });

我的編譯器(VC++ 2019)仍然抱怨同樣的錯誤。 很好奇,我試着手動寫了一個find function 看看發生了什么,但我沒有成功,得到了同樣的錯誤:

auto iter = funcs.begin();
for (; iter != funcs.end(); iter++)
    if (*iter->target<void()>() == myFunc2)
        break;

所以這就是問題所在。 如何比較 2 個std::function對象以查看它們是否存儲相同的 function?

如此處所示,模板成員 function target接受與存儲的 object 類型進行比較的類型。 在您的情況下,它是指向 function 的指針 你必須改變

*iter->target<void()>() == myFunc2

*iter->target<void(*)()>() == myFunc2

Note that this will only only you to find a plain C function, not an arbitrary callable object (like a lambda function). 我認為您應該考慮在這里使用普通指針而不是std::function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM