Search code examples
c++c++11dlazy-evaluation

Laziness in C++11


Do you know how to perform a lazy evaluation of string, like in this D snippet:

void log(lazy string msg) {
  static if (fooBarCondition)
    writefln(…) /* something with msg */
}

Actually, the problem might not need laziness at all since the static if. Maybe it’s possible to discard char const* strings when not used? Like, in C++:

void log(char const *msg) {
  #ifdef DEBUG
  cout << … << endl; /* something with msg */
  #else /* nothing at all */
  #endif
}

Any idea? Thank you.


Solution

  • #ifdef DEBUG
    #define log(msg) do { cout << … << endl; } while(0)
    #else
    #define log(msg) do { } while(0)
    #endif
    

    There are two ways to achieve laziness in C++11: macros and lambda expressions. Both are not "lazy" technically, but what is called "normal evaluation" (as opposed to "eager evaluation"), which mean that an expression might be evaluated any number of times. So if you are translating a program from D (or haskell) to C++ you will have to be careful not to use expressions with side effects (including computation time) in these expressions.

    To achieve true laziness, you will have to implement memoizing, which is not that simple.

    For simple logging, macros are just fine.