简体   繁体   中英

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. :-)
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. 目前还不完全清楚你要求的是什么...最好的,我想使用像GWT这样的东西,而是将Java源码编译成JavaScript源码它会将ScalaHaskellF#编译成C++源代码,但是因为我没有相信这样的事情存在,我想有一些东西......乐于助人。 I appreciate the suggested anon functions, for example.

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).

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

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 .

看一下Boost.Phoenix库,它使您能够在C ++中编写close(er)函数式编程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM