简体   繁体   English

定义std :: hash <std::function>

[英]Define std::hash<std::function>

I need to create a templated class that can hold pointers to elements of type T and then performs functions on them. 我需要创建一个模板化的类,它可以保存指向T类型元素的指针,然后对它们执行函数。 The functions will come from different places, so I need a container to store them, so I can call them later. 这些函数来自不同的地方,所以我需要一个容器来存储它们,所以我可以稍后调用它们。 I decided to use an std::unordered_set , because it offers speed and restricts duplication due to it being implemented as a hash table. 我决定使用std::unordered_set ,因为它提供了速度并限制了重复,因为它被实现为哈希表。 I have a whole class written, but it doesn't compile due to there not being a hash function defined for my std::function that takes a pointer of type T and returns void . 我编写了一个完整的类,但它没有编译,因为没有为我的std::function定义的哈希函数,它接受类型为T的指针并返回void It's easy enough to specify it with struct hash<std::function<void(MyCustomType*)>> (and overloading the () operator, too) for each type I use, but how do I actually hash the function? 对于我使用的每种类型,使用struct hash<std::function<void(MyCustomType*)>> (以及重载()运算符)很容易指定它,但是我如何实际散列函数呢?

Here is a watered-down excerpt from my class with the relevant members and methods: 以下是我班级与相关成员和方法的详细摘录:

template <typename T>
class Master {
private:
    std::unordered_set<std::function<void(T*)>> functions;
protected:
    registerFunction(std::function<void(T*)> function) {
        this->functions.insert(function);
    }
    unregisterFunction(std::function<void(T*)> function) {
        this->functions.erase(function);
    }
};

I'm not completely bound to using an std::unordered_set , but it seems to offer everything that I'd need to get this piece (and the rest of my code) working well. 我并不完全限制使用std::unordered_set ,但它似乎提供了我需要的所有内容(以及我的其余代码)运行良好。

Am I thinking about this the wrong way? 我是否以错误的方式思考这个问题? Is it completely impossible to hash a std::function ? 散列std::function是完全不可能的吗?

A set is mostly something you will check that data is in it. 一个集合主要是你将检查其中的数据。

So I do not see the point of using one here... You'll have your functions and you'll store them in the set, and after that, what ? 所以我没有看到在这里使用它的意义...你将拥有你的功能,你将它们存储在集合中,然后,什么? You just iterate on them ? 你只是迭代它们?

For your question, a element of a set should have a way to generate a hash and an operator==() . 对于您的问题,集合的元素应该有一种方法来生成哈希和operator==() The second is not provided for std::function and thus you wouldn't be able to check that your function is really in the set. 第二个没有为std::function ,因此你无法检查你的函数是否真的在集合中。

So even if you find a way to generate an hash from the function, you would be stuck... And I do not see how to meet the hash requirement. 所以,即使你找到了一种从函数生成哈希的方法,你也会被卡住......而且我不知道如何满足哈希要求。

Why not simply use a std::vector ? 为什么不简单地使用std::vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM