std::function 与函数指针
std::function 可以代替函数指针
bool IsEmpty(const std::string& str)
{
return str.empty();
}
typedef bool (*pIsEmpty)(cosnt std::string& str);
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
std::string str("Hello");
is_empty f = IsEmpty;
std::cout << str << " is empty :" << f(str) << std::endl;
pIsEmpty pf = &IsEmpty;
std::cout << str << " is empty :" << pf(str) << std::endl;
return 0;
}
打印
Hello is empty :0
Hello is empty :0
std::function 与 Functor
Functor 是一种类函数化的方式
定义一个 Functor
class IsEmpty_Class {
public:
bool operator()(const std::string& str)
{
return str.empty();
}
};
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
std::string str("Hello");
IsEmpty_Class c;
is_empty f = c;
std::cout << str << " is empty :" << c(str) << std::endl;
std::cout << str << " is empty :" << f(str) << std::endl;
return 0;
}
打印
Hello is empty :0
Hello is empty :0
std::function 与 lambda
lambda 是 C++11 的新特性,为了连贯,我们定义一个 lambda
// lambda
auto IsEmpty_Lambda =
[](const std::string& str)
-> bool {
return str.empty();
};
using is_empty = std::function<bool(const std::string& str)>;
int main()
{
std::string str("Hello");
is_empty f = IsEmpty_Lambda;
std::cout << str << " is empty :" << f(str) << std::endl;
std::cout << str << " is empty :" << IsEmpty_Lambda(str) << std::endl;
return 0;
}
打印
Hello is empty :0
Hello is empty :0
std::function 延迟绑定
std::bind 绑定调用对象和对象参数,绑定后的结果可以使用 std::function 进行保存,类似一个委托对象。
class IsEmpty_Class_Member {
public:
bool isEmpty(const std::string& str)
{
return str.empty();
}
std::string str = "Hello";
};
int main()
{
IsEmpty_Class_Member cm;
is_empty f = std::bind(&IsEmpty_Class_Member::isEmpty, &cm, std::placeholders::_1);
std::cout << str << " is empty :" << f(str) << std::endl;
std::function<std::string&(void)> cmf_str = std::bind(&IsEmpty_Class_Member::str, &cm);
cmf_str() = "Hello Wolrd"; // 由于绑定 cm 引用,可以外部更改 cm 值
std::cout << "IsEmpty_Class_Member str :" << cm.str << std::endl;
return 0;
}
打印
Hello is empty :0
IsEmpty_Class_Member str :Hello Wolrd