c++ boost lambda libraries

妖精的绣舞 提交于 2019-12-04 09:30:56

Remaining within the boundaries of the C++ language and libraries, I would suggest first getting used to programming using STL algorithm function templates, as one the most common use you will have for boost::lambda is to replace functor classes with inlined expressions inlined.

The library documentation itself gives you an up-front example of what it is there for:

for_each(a.begin(), a.end(), std::cout << _1 << ' ');

where std::cout << _1 << ' ' produces a function object that, when called, writes its first argument to the cout stream. This is something you could do with a custom functor class, std::ostream_iterator or an explicit loop, but boost::lambda wins in conciseness and probably clarity -- at least if you are used to the functional programming concepts.

When you (over-)use the STL, you find yourself gravitating towards boost::bind and boost::lambda. It comes in really handy for things like:

std::sort( c.begin(), c.end(), bind(&Foo::x, _1) < bind(&Foo::x, _2) );

Before you get to that point, not so much. So use STL algorithms, write your own functors and then translate them into inline expressions using boost::lambda.

From a professional standpoint, I believe the best way to get started with boost::lambda is to get usage of boost::bind understood and accepted. Use of placeholders in a boost::bind expression looks much less magical than "naked" boost::lambda placeholders and finds easier acceptance during code reviews. Going beyond basic boost::lambda use is quite likely to get you grief from your coworkers unless you are in a bleeding-edge C++ shop.

Try not to go overboard - there are times when and places where a for-loop really is the right solution.

Depends. Are you already well versed in functional programming concepts? If not, I'd suggest that you start in a language that is designed for functional programming instead of a procedural language with functional features stapled on. If you aren't used to coding in a functional style (it's not harder necessarily, but it's definitely different), then you'll spend more time fighting the syntax and not enough time learning to get stuff done.

As for where to start, I cut my functional teeth on Scheme, but there are plenty of good options.

If you are working with a reasonably recent compiler, you can use boost. If it's not on your machine already, install it (sudo apt-get install libboost-dev on unbuntu, get the binaries from boost.org if you are on windows). Read the doc's then look at your existing code for situations where you might use them. Do you have a lot of code duplication that could be eliminated if you parametrized a function with a small piece of code, for example?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!