effective c++ 条款02:尽量以const, enum, inline替换#define

记住:

对于单纯常量,最好以const对象或者enum替换#define。

对于形似函数的宏,最好改用inline函数替换。

 

#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653; //better

 

const char* const author = "pfsi";
const std::string author("pfsi"); //better

 

scores数组用到了NumTurns,所以必须在类定义中给NumTurns赋值。

// gp.h
class GamePlayer {
private:
    static const int NumTurns = 5;
    int scores[NumTurns];
};

// main.cc
#include "gp.h"
int main()
{
    GamePlayer gp;
}

如果某些编译器不支持这个,可以采用#define

class GamePlayer {
private:
    #define NumTurns 5
    int scores[NumTurns];
};

但有个缺点,不能把#define的作用域限定在类中。一旦宏被定义,知道#undef,一直有效。

比较好的替换方案是用enum

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

 

如果在类定义中不需要用到NumTurns,那就可以在类实现文件中赋值。

// gp.h
class GamePlayer {
private:
    static const int NumTurns;
};

// gp.cc
#include "gp.h"

const int GamePlayer::NumTurns = 5;

 

#define 宏操作的问题

#include <iostream>
using namespace std;

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

void func(const int x)
{
    cout << x << endl;
}

int main()
{
    int a = 5, b = 0;
    CALL_WITH_MAX(++a, b);       //a被累加二次
    CALL_WITH_MAX(++a, b+10);    //a被累加一次
}

 一种解决办法是宏中定义临时变量

#include <iostream>
using namespace std;

#define CALL_WITH_MAX(a, b) \
    do { \
        typeof(a) _a = (a); typeof(b) _b = (b);  func((_a) > (_b) ? (_a) : (_b)); \
    } while(0)

void func(const int x)
{
    cout << x << endl;
}

int main()
{
    int a = 5, b = 0;
    CALL_WITH_MAX(++a, b);       //a被累加一次
    CALL_WITH_MAX(++a, b+10);    //a被累加一次
}

或者使用模板

#include <iostream>
using namespace std;

void func(const int x)
{
    cout << x << endl;
}

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

int main()
{
    int a = 5, b = 0;
    callWithMax(++a, b);       //a被累加一次
    callWithMax(++a, b+10);    //a被累加一次
}

 

posted @ 2018-06-08 11:34  pfsi  阅读(178)  评论(0编辑  收藏  举报