- 对于单纯常量,最好以 const 对象或 enums 替换 #defines
- 对于形似函数的宏(macros),最好改用 inline 函数替换 #defines
- 宁以编译器替换预处理器。
在C++中,常量成员、静态成员不能在类内初始化。必须在类内声明,在类外初始化。
要使用类内初始化语法,常量必须是由常量表达式初始化的整数或枚举类型的静态常量
class Tset {
static const int a = 1; //OK
enum {b = 5} //OK
const int c3 = 7; // error: not static
static int c4 = 7; // error: not const
static const float c5 = 7; // error: not integral
};
enum hack
- enum hack 的行为某方面说比较像 #define 而不像 const
- enum hack 是 template metaprogramming(模板元编程) 的基础技术
宏函数的编写比较麻烦,容易引起意想不到的错误(虽然可以通过加小括号来解决)。
//以a和b的较大值调用f
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
我们可以使用 template inline 函数
,同样
template<typename T> //由于我们不知道
inline void callWithMax(const T& a, const T& b){//T是什么,所以采用
f(a >b ? a: b); //pass by reference-to-const
}