Roger I Martin - 2014-05-05

Hi

I've been experimenting with c++11 lambda function for the eval of

int scale=23.06;
eoEvalFuncPtr<EOT> mainEval([&](const EOT & _indi) -> double{
    return _indi.fitness()*_indi.fitness();
    double sum = 0;
    for (unsigned i = 0; i < _indi.size(); i++)
        sum += _indi[i]*_indi[i];
    return (-sum);            // maximizing only
} );
eoEvalFuncCounter<EOT> eval(mainEval);

compiles and works. But when the referenced variable 'scale' is multiplied inside the lambda function, then the signature of the lambda function wouldn't happily compile:

int scale=23.06;
eoEvalFuncPtr<EOT> mainEval([&](const EOT & _indi) -> double{
    return _indi.fitness()*_indi.fitness();
    double sum = 0;
    for (unsigned i = 0; i < _indi.size(); i++)
        sum += _indi[i]*_indi[i];
    //use lambda referenced variable in here
    return scale*(-sum);            // maximizing only
} );
eoEvalFuncCounter<EOT> eval(mainEval);

The above failed until I patched the eoEvalFuncPtr.h as below. Now this makes the c++11 language spec or younger required and this change might not be good for development with older compilers and without the -std=c++11 switch. I haven't found a way to do it yet without http://en.cppreference.com/w/cpp/utility/functional which is since c++11 and still get lambda functions to compile. Yet the lamda function really simplifies coding a complicated, cluster involving, fitness calculation/evaluation!

diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h
index f4952c2..119256b 100644
--- a/eo/src/eoEvalFuncPtr.h
+++ b/eo/src/eoEvalFuncPtr.h
@@ -29,6 +29,7 @@
 #define EOEVALFUNCPTR_H

 #include <eoEvalFunc.h>
+#include <functional>

 /** EOEvalFuncPtr: This class
  * takes an existing function pointer and converts it into a evaluation
@@ -53,15 +54,18 @@
   eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) )
     : eoEvalFunc<EOT>(), evalFunc( _eval ) {};

+  eoEvalFuncPtr(std::function< FitT( FunctionArg )> _eval)
+    : eoEvalFunc<EOT>(), evalFunc( _eval ) {};
+
   /// Effectively applies the evaluation function to an EO
   virtual void operator() ( EOT & _eo )
   {
     if (_eo.invalid())
-        _eo.fitness((*evalFunc)( _eo ));
+        _eo.fitness(evalFunc( _eo ));
   };

   private:
-    FitT (* evalFunc )( FunctionArg );
+    std::function< FitT( FunctionArg )> evalFunc;
 };

 #endif