ryskajakub
ryskajakub

Reputation: 6431

metaprogram c++ code

New semester in my university started and I am once again "forced" to quit abstractions and explore the deep waters of low level programming in c++. My mind is already partially contamined with folds, high order functions, etc., and I don't find any fun in writing for example:

bool allEven = true;
for(int i = 0; i < arr.length; i++){
   if (arr[i] % 2 != 0){
      allEven = false; 
      break;
   }
}
when I know that I can write val allEven = arr forall (_ % 2 == 0).
My question is: is there any tool|technique|language construct|metaprogramming stuff, that can bring some c++ code without writing it actually? I need to the whole source but it can be eventually obfuscated, only machine is going to process it.
And please don't me accuse of being lazy, I value it as one of my best virtues. :-)
EDIT It's not entirely clear what are you asking for... At best, I would like to use something like GWT but instead compiling Java sources to JavaScript sources It would compile Scala or Haskell or F# to C++ sources, but since I don't believe that something like this exists, I would like to have something... helpful. I appreciate the suggested anon functions, for example.

Upvotes: 6

Views: 277

Answers (4)

rafak
rafak

Reputation: 5551

With new algorithms in C++0x, there is all_of:

bool all_even = std::all_of(arr.begin(), arr.end(),
                            [](int i) { return i%2 == 0; });

Boost.Range allows less verbosity:

bool all_even = 
    0==boost::count_if(arr, [](int i){ return i%2 != 0;});

Hopefully, Boost.Range will soon offer all_of.

Upvotes: 2

Edward Strange
Edward Strange

Reputation: 40895

bool is_even = std::find_if(arr.begin(), arr.end(), [](int i) { return i%2 != 0; }) == arr.end();

Upvotes: 3

wilx
wilx

Reputation: 18268

Take a look at Boost.Phoenix library, it enables you to write close(er) to functional style of programming in C++.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490713

It's not entirely clear what you're really asking for, but if you're trying to write C++ that's more like your other code, you could do something like this:

bool allEven = 
    std::accumulate(arr.begin(), arr.end(), [](bool a, int i) {return a && i & 1==0; }, 1);

This does use a lambda, which is new in C++0x. If you're using an older compiler that doesn't support lambdas, you could look into using Boost Lambda instead (in which case your code would be even closer to the example you've given).

Upvotes: 3

Related Questions