Thursday, 15 April 2010

c++ - Embed different functions in a function: functor or lambda? -


I am writing the program in C ++ that I have different values ​​for the same in loop Function should be embedded

Example:

 For  (i = 0; i & lt; N_ITER; i ++) {/ * ... * / function_A ( ); For / * ... * /} (i = 0; i  me inline  function_A  and  function_B   my first solution in this function uses Functors and Function templates as follows:  
  class function_A {public: void operator () () {/ * ... *}}; Square function_B {public: zero operator () ()) {/ * ... *}}; Template & lt; Class T & gt; Class run {public: zero operator () () (/) ... * / t funk; For (i = 0; i   

And I can call the function like this:

 run  & lt; Function_A & gt; () () (); To run & lt; Function_B & gt; () () ();   

But soon I came to know that too many repetitive monorector definitions class xxx {public: zero operator () () {...}}; In code and it looks strange.


So I changed to a solution using lambda:

  automatic function_A = [] () {/ * ... *}; Auto function_b = [] () {/ * ... * /}; Template & lt; Class T & gt; Class run {public: T-Funk; Run (T Funk): Funk (throw) {} Zero operator () () {/ * ... * for (i = 0; i   

But this time it is difficult to call these tasks:

 run  & lt; Decltype (function_A) & gt; FuncA (function_A); FuncA (); To run & lt; Decltype (function_A) & gt; FuncB (function_A); FuncB ();   

And this is not as clear as the previous solution.


Is this a more elegant way to implement it in C ++? Am I forgetting something? Any suggestions would be appreciated!

Try it out:

  Zero run (std :: function & Lt; void (zeros)> fn) {for (int i = 0; i & lt; N_ITER; i ++) fn (); } (...) Auto lambda 1 = [] () {std :: cout & lt; & Lt; "Hello, world! \ N"; }; Run (lambda1); After formatting   

function / method, you will be able to do it properly too:

  class C {Public: Zero Operator () () () {printf ("Hello World for Factor! \ N"); }}; (...) cc; Run (c);   

Edit : In response to comments:

The last solution was not inline. However, it was:

  template & lt; Typename T & gt; Zero run 2 (tfn) {for (int i = 0; i   

Disassembly:

  auto lambda 1 = [] () {std :: cout & lt; & Lt; "Hello, world! \ N"; }; Run2 (lambda1); 002 E 1280 mov ecx, dword ptr ds: [2E3044h] 002 E 1286 call std :: operator   

Actually, the solution with Factor in the case of Run 2 Was also applied for a little while:

  cc; Run2 (c); 01031293 MOV SEI, 0 EH 01031298 JMP Main + 30H (010312AH) 0103129A Li Abex, [EBKS] 010312A MOG EquAx, Dvord PTR DS: [1033044 H] \ 010312A 6 mov ADX, 10331AC | 010312 AB Call Study :: Operator <; & Lt; & Lt; Std :: char_traits & lt; Four & gt; & Gt; (01031750 h) & gt; Loop 010312 Bd Dec Sc. 010312 B1 JNE Main + 30 H (010312AH) /    

No comments:

Post a Comment