Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Maintaining state === Another advantage of function objects is their ability to maintain a state that affects <code>operator()</code> between calls. For example, the following code defines a [[generator (computer science)|generator]] counting from 10 upwards and is invoked 11 times. <syntaxhighlight lang="cpp"> #include <algorithm> #include <iostream> #include <iterator> class CountFrom { public: CountFrom(int count) : count_(count) {} int operator()() { return count_++; } private: int count_; }; int main() { const int state(10); std::generate_n(std::ostream_iterator<int>(std::cout, "\n"), 11, CountFrom(state)); } </syntaxhighlight> In C++14 or later, the example above could be rewritten as: <syntaxhighlight lang="cpp"> #include <algorithm> #include <iostream> #include <iterator> int main() { std::generate_n(std::ostream_iterator<int>(std::cout, "\n"), 11, [count=10]() mutable { return count++; }); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)