c ++ typedef std::function<> 如何使用?
c ++ typedef std::function<> How to use?
嗨,我正在做这个项目,在标题中定义了以下内容的文件
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");
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 是否需要使用 - &gt;运算符在C 中调用成员函数时
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- 基例如何影响使用递归函数的哪些行