[Effective C++] 尽量以const、enum、inline替换#define

使用#define的几种典型场景:

  • 定义常量;
  • 实现宏函数;

使用#define定义常量的问题在于:

  1. 在经过预处理器后替换后,每个常量都变成了孤零零的值,增加了调试难度以及二进制体积;
  2. #define定义的常量缺乏作用域的概念,无法实现class常量这一概念;

针对第一点,我们只需要将往常的#define定义式改写成const即可。

比如说将

#define ASPECT_RATIO    1.653

改写成

const double AspectRatio = 1.653;

即可。

针对第二点,#define定义的常量是无法实现class的封装性的,为此我们可以有两种选择:


class GamePlayer {
private:
    static const int NumTurns = 5;  // declaration
    int scores[NumTurns];

};

const int GamePlayer::NumTurns;     // definition

class GamePlayer {
private:
    enum { NumTurns = 5 };  // enum type
    int scores[NumTurns];

};


使用#define实现宏函数的种种大坑,自然不必多言。

针对宏函数,C++中可以使用template inline function来进行代替;

更重要的一点是,集简单、效率、类型安全、不会有莫名奇妙的bug于一身。

比如说可以用

template<typename T>
inline void callWithMax(const T& a, const T& b)
{
    f(a > b ? a : b);
}

替换

#define CALL_WITH_MAX(a, b) f((a) > (b)) ? (a) : (b))

猜你喜欢

转载自blog.csdn.net/sai_j/article/details/79449016
今日推荐