是否有一个std :: function的用例不被函数指针覆盖,还是只是语法糖? [英] Is there a use case for std::function that is not covered by function pointers, or is it just syntactic sugar?
问题描述
与函数指针相比,std :: function的符号是相当不错的。但是,除此之外,我找不到一个用例,它不能被指针替换。因此,它只是函数指针的语法糖?
The notation for std::function is quite nice when compared to function pointers. However, other than that, I can't find a use case where it couldn't be replaced by pointers. So is it just syntactic sugar for function pointers?
推荐答案
std :: function< code>提供了封装任何类型的可调用对象的可能性,这是函数指针不能做的事情(尽管非捕获 lambdas可以转换为函数指针)。
std::function<>
gives you the possibility of encapsulating any type of callable object, which is something function pointers cannot do (although it is true that non-capturing lambdas can be converted to function pointers).
为了让您了解您可以实现的灵活性:
To give you an idea of the kind of flexibility it allows you to achieve:
#include <functional>
#include <iostream>
#include <vector>
// A functor... (could even have state!)
struct X
{
void operator () () { std::cout << "Functor!" << std::endl; }
};
// A regular function...
void bar()
{
std::cout << "Function" << std::endl;
}
// A regular function with one argument that will be bound...
void foo(int x)
{
std::cout << "Bound Function " << x << "!" << std::endl;
}
int main()
{
// Heterogenous collection of callable objects
std::vector<std::function<void()>> functions;
// Fill in the container...
functions.push_back(X());
functions.push_back(bar);
functions.push_back(std::bind(foo, 42));
// And a add a lambda defined in-place as well...
functions.push_back([] () { std::cout << "Lambda!" << std::endl; });
// Now call them all!
for (auto& f : functions)
{
f(); // Same interface for all kinds of callable object...
}
}
As usual, see a live example here. Among other things, this allows you to realize the Command Pattern.
这篇关于是否有一个std :: function的用例不被函数指针覆盖,还是只是语法糖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!