Implement closure of C ++ for local classes

Source: Internet
Author: User

First of all, although closures are often mentioned, I am not clear about the concept of closures. I vaguely feel that if function A defines and Returns function B, function B can still run normally outside function A and access the variables defined in function A. At the same time, the variables defined in function A cannot be accessed externally, it's called a closure-if this is wrong, it should be something I did not say!

Some people have written a blog saying that the closure is implemented through the new feature std: bind of C ++ 11. After thinking about it carefully, it can be implemented through the two features of C ++ 03: one is a local class and the other is a static local variable.

Static local variables

C ++ allows you to define static local variables within the function. These variables will not be destroyed when they exit the function, just like this.

     
     
  1. void func() { 
  2.     static int i = 0; 
  3.     cout << i++ << endl; 

If you call func multiple times, you will find that the value output to the console is increasing progressively.

Local class

It is impossible to define a local function in a function. C ++ does not have this syntax. However, you can define a local class in a function. This class can only be used in this function. It is very interesting, just like this.

     
     
  1. Void func (){
  2. Class LocalClass {
  3. Private:
  4. // Define private members
  5. Public:
  6. Void run (){
  7. //......
  8. }
  9. } Obj;
  10. Obj. run ();
  11. }

If you want to return a local class object to the outside, you need to define an interface to receive the returned object and call the method. At the same time, use new in the function to generate an object and return its pointer, just like this

     
     
  1. class ILocal { 
  2. public: 
  3.     virtual void run() = 0; 
  4. }; 
  5.  
  6. ILocal* func() { 
  7.     class LocalClass: public ILocal { 
  8.     public: 
  9.         virtual void run() { 
  10.             // ...... 
  11.         } 
  12.     }; 
  13.     return new LocalClass(); 

The basic knowledge is ready. Let's talk about the process of implementing the closure below. Let's take a look at the annotations.

 
 
  1. # Include <iostream>
  2. Using namespace std;
  3.  
  4. ////// Interface implementation ///////////////////////////// ///////////
  5. // Define a function object interface ...... Just like C # Delegation
  6. Class ITest {
  7. Public:
  8. // This operator is defined mainly for calling like a function, like this: obj ();
  9. Void operator ()(){
  10. Process ();
  11. }
  12.  
  13. Protected:
  14. // Interface function
  15. Virtual void process () = 0;
  16. };
  17.  
  18. // The following function returns an ITest object pointer.
  19. ITest * test (){
  20. // The static variables in the function are not destroyed if you leave the function, and can
  21. Static int count = 0;
  22.  
  23. // Define a local class
  24. Class Test: public ITest {
  25. Public:
  26. // Implement the interface functions defined in ITest for operations
  27. Virtual void process (){
  28. Cout <"Count is" <count ++ <endl;
  29. }
  30. };
  31.  
  32. // Return a new object ...... New is required here, you know
  33. Return new Test ();
  34. }
  35.  
  36. /////// Function implementation ///////////////////////////// ///////////
  37. // Define the pointer type of the test function
  38. Typedef void (* Func) (const char *);
  39.  
  40. // The following function returns a function in the closure.
  41. Func testFunc (){
  42. // Static local variable Initialization is 100
  43. Static int count = 100;
  44. // Static local constant
  45. Static const char * const NAME = "James ";
  46.  
  47. // Functions cannot be defined directly, so you have to define static methods of local classes and return their pointers.
  48. Class Test {
  49. Public:
  50. // This definition can be used to input parameters. Likewise, there can be returned values.
  51. Static void process (const char * pName = NULL ){
  52. If (pName = NULL) {pName = NAME ;}
  53. Cout <pName <"Count is" <count -- <endl;
  54. }
  55. };
  56. Return Test: process;
  57. }
  58.  
  59. //// // Program entry: main function //////////////////////////////////
  60. Int main (int argc, char * argv []) {
  61. ITest * pT = test ();
  62. Func pF = testFunc ();
  63.  
  64. // The functions and objects returned from the function after multiple calls. Observe the results.
  65. For (int I = 0; I <10; I ++ ){
  66. (* PT )();
  67. PF (I % 2 = 0 )? NULL: "Fancy ");
  68. }
  69. }

Give a running result

 
 
  1. Count is 0 
  2. James Count is 100 
  3. Count is 1 
  4. Fancy Count is 99 
  5. Count is 2 
  6. James Count is 98 
  7. Count is 3 
  8. Fancy Count is 97 
  9. Count is 4 
  10. James Count is 96 
  11. Count is 5 
  12. Fancy Count is 95 
  13. Count is 6 
  14. James Count is 94 
  15. Count is 7 
  16. Fancy Count is 93 
  17. Count is 8 
  18. James Count is 92 
  19. Count is 9 
  20. Fancy Count is 91 

C ++ is a very flexible language. What we usually use is just the tip of the iceberg compared with C ++ Specification. Although I have not used it since year 45 due to my work relationship, it is still one of my favorite languages.

This article from the "Edge City inn xuehai Wuxi" blog, please be sure to keep this source http://jamesfancy.blog.51cto.com/2516291/1166900

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.