std::function
implements a technique called type-erasure because of which you can store any callable entity in std::function
, be it functors, member functions, or free functions — you can even store member-data as well which seems counter intuitive!
Here is one example, which cannot be done without std::function
(or type-erasure):
std::vector<std::function<void()>> funs;
for(int i = 0; i < 10; ++i)
funs.push_back([i] { std::cout << i < std::endl; });
for(auto const & f: funs)
f();
Here is another example which stores member-data:
struct person
{
std::string name;
};
int main()
{
std::vector<person> people {
{"Bjarne"},
{"Alex"}
};
std::function<std::string(person const&)> name (&person::name);
for(auto const & p : people)
std::cout << name(p) << std::endl;
}
Output (demo):
Bjarne
Alex
Hope that helps.