- 宏实现
1. 宏定义有可能从未被编译器看到,找不到宏定义
2. 宏有可能存在多份
#define ASPECT_RATIO 1.653
1. 宏实现函数,必须为宏中所有实参加上(),即使加上也会有被多次调用
template<typename T> inline void print(T data) {std::cout << data << std::endl; }#define CALL_WITH_MAX(a,b) print((a)>(b)?(a):(b)) void Test00() {int a(5), b(0);CALL_WITH_MAX(++a, b); //a>b,两个(a)会执行两次++a;CALL_WITH_MAX(++a, b + 10); //b>a, 一个(a)执行一次++a; }
- 常量实现
1. 语言常量,编译器肯定会看到
2. 不会存在多份,减少代码量
const double AspectRatio = 1.653;
1. 指针和所指内容均为常量
const char* const authorName = "Scott Meyers";
1. 类作用域的常量至多一份,必须成为static
2. 宏不重视作用域
class GamePlayer00 { private:static const int NumTurns = 5;int scores[NumTurns]; };class GamePlayer01 { private:enum{NumTurns = 5};int scores[NumTurns]; };
1. template inline函数不需要函数本体加(),也不需要担心参数被核算多次
2. template inline函数遵守作用域和访问规则
template<typename T> inline void callWithMax(const T& a, const T& b) {print(a > b ? a : b); }void Test01() {int a(5), b(0);callWithMax(++a, b); //a>b,执行一次++a;callWithMax(++a, b + 10); //b>a, 执行一次++a; }int main() {Test00();Test01();return EXIT_SUCCESS; }