设为首页 加入收藏

TOP

Item 2: Prefer consts, enums, and inlines to #defines.(5)
2013-10-07 14:25:33 来源: 作者: 【 】 浏览:55
Tags:Item Prefer consts enums and inlines #defines.

Here, the number of times that a is incremented before calling f depends on what it is being compared with!

Fortunately, you don’t need to put up with this nonsense. You can get all the efficiency of a macro plus all the predictable behavior and type safety of a regular function by using a template for an inline function (see Item 30):

  1. template  // because we don’t  
  2. inline void callWithMax(const T& a, const T& b)  // know what T is, we  
  3. {  // pass by reference-  
  4.         f(a > b   a : b);  // const — see Item 20  

This template generates a whole family of functions, each of which takes two objects of the same type and calls f with the greater of the two objects. There’s no need to parenthesize parameters inside the function body, no need to worry about eva luating parameters multiple times, etc.

Furthermore, because callWithMax is a real function, it obeys scope and access rules. For example, it makes perfect sense to talk about an inline function that is private to a class. In general, there’s just no way to do that with a macro.

Given the availability of consts, enums, and inlines, your need for the preprocessor (especially #define) is reduced, but it’s not eliminated. #include remains essential, and #ifdef/#ifndef continue to play important roles in controlling compilation. It’s not yet time to retire the preprocessor, but you should definitely give it long and frequent vacations.

Things to Remember

For simple constants, prefer const objects or enums to #defines.

For function-like macros, prefer inline functions to #defines.


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇详细介绍Java中的堆和栈 下一篇Item 2: Prefer consts, enums, a..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: