C++ c++;typedef标准::函数<&燃气轮机;如何使用?
嗨,我在这个项目上工作,在文件头中定义了以下内容C++ c++;typedef标准::函数<&燃气轮机;如何使用?,c++,C++,嗨,我在这个项目上工作,在文件头中定义了以下内容 typedef std::function<unsigned int(const std::string&)> HashFunction; 程序崩溃。类型为std::function的对象的行为非常类似于指向带有签名的函数的函数指针。默认构造的std::function并不指向任何函数。std::function和函数指针Signature*之间的关键区别在于,可以在std::function中以函数对象的形式拥有某些状态
typedef std::function<unsigned int(const std::string&)> HashFunction;
程序崩溃。类型为
std::function
的对象的行为非常类似于指向带有签名的函数的函数指针。默认构造的std::function
并不指向任何函数。std::function
和函数指针Signature*
之间的关键区别在于,可以在std::function
中以函数对象的形式拥有某些状态
要使用这种类型的对象,您需要使用合适的函数初始化它,例如
#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");
}
#包括
typedef std::function HashFunction;
结构散列{
无符号整数运算符()(std::string const&s)const{
返回0;//这是一个非常糟糕的散列!这里有一个更好的实现
}
};
int main(){
哈希函数hash{hash()};
哈什(“你好”);
}
如果该函数对象实际引用了一个函数,可能会有很大帮助,或任何其他标准库类,然后再开始使用它们。谢谢。当我使用HashFunction hash{hash()}代码>它给了我这样一个错误;预计在hash@user2407736:至少这个用途是为了发挥作用。我将把这个示例更新为一个完整的程序代码>,它不属于那里,并停止了程序的编译。
#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");
}