c ++ typedef std::function<> 如何使用?

c ++ typedef std::function<> How to use?

本文关键字:gt 何使用 lt typedef function std      更新时间:2023-10-16

嗨,我正在做这个项目,在标题中定义了以下内容的文件

typedef std::function<unsigned int(const std::string&)> HashFunction;

我究竟如何在我的哈希函数中使用它?当我尝试时

HashFunction myHashFunction;
myHashFunction("mystring");

程序崩溃。

类型为 std::function<Signature> 的对象的行为非常类似于指向具有签名Signature的函数的函数指针。默认构造std::function<Signature>只是不指向任何函数。std::function<Signature> 和函数指针Signature*之间的主要区别在于,您可以在 std::function<Signature> 中以函数对象的形式具有某种状态。

要使用这种类型的对象,您需要使用合适的函数对其进行初始化,例如

#include <functional>
typedef std::function<unsigned int(const std::string&)> HashFunction;
struct Hash {
    unsigned int operator()(std::string const& s) const {
        return 0; // this is a pretty bad hash! a better implementation goes here
    }
};
int main() {
    HashFunction hash{ Hash() };
    hash("hello");
}