用元编程方式编写C++代码

6

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.


@coubeatczech val allEven = arr forall (_ % 2 == 0) 你是在用C++做这个吗?... - clamchoda
@Chris Buckler:我猜他是在用F#,并且对自己无法在C++中做同样的事感到沮丧。 - Chuck
那其实是Scala,但是仍然感到沮丧。 - ryskajakub
3
尽管我理解并同意以功能为导向的写作方式,但当你在罗马时,要像罗马人一样做。不要试图像Scala一样编写C ++; 这将和像C ++一样编写Scala一样糟糕。如果你正在使用命令式语言,就写命令式代码吧。以后维护代码的其他人会感激你的。 - Onorio Catenacci
顺便问一句,第一行不应该是“bool allEven = true;”吗? - Onorio Catenacci
@Chuck 啊,我现在明白他在问什么了,谢谢 Chuck! - clamchoda
4个回答

3

不太清楚您究竟要求什么,但如果您想编写更像其他代码的C++代码,可以这样做:

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

这里使用了lambda,它是C++0x中的新特性。如果你使用的是不支持lambda的旧编译器,你可以考虑使用Boost Lambda代替(这样你的代码就更接近你给出的示例了)。


这里使用 find_if 不是更简单一些吗? - templatetypedef
@templatetypedef:是的,但我尽可能地试图模仿他所写的内容。 - Jerry Coffin
累加器是一个“折叠”函数,我猜? - ryskajakub

3

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

这段代码是用于判断一个数组中所有的元素是否都是偶数。使用了 C++ 中的 STL 库,通过 `std::find_if` 函数和 Lambda 表达式来过滤出数组中的奇数元素。最终返回值为一个布尔类型的变量 `is_even`,如果等于数组结尾,则说明数组中所有元素均为偶数。

2

在C++0x中,有新的算法,其中包括all_of

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

Boost.Range允许更少的冗长:
bool all_even = 
    0==boost::count_if(arr, [](int i){ return i%2 != 0;});

希望Boost.Range很快能提供all_of功能。

1

看看Boost.Phoenix库,它使你能够在C++中更接近函数式编程风格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接