C/C++预处理表达式中可接受的内容

因为C++里推荐用枚举来代替宏定义,因而在C++代码中都很少使用宏定义。

但是现在碰到一个需求,就是希望在编译的时候知道两个常数是否一致(比如两个版本号),第一反应就是用#if,但是结果发现#if根本不能接受enum, 甚至不能接受const:


//============CLASS ENUM==========

class A {

    enum {
        CLASS_ENUM_A = 1
    };

};


class B {

    enum {
        CLASS_ENUM_B = 2
    };

};


#if A::ENUM_A != B::ENUM_B	//error: token "::" is not valid in preprocessor expressions|
    #error "class enum A != B"
#endif // A




//===================NORMAL ENUM========================


enum {
    ENUM_A = 1,
    ENUM_B = 2
};


#if ENUM_A != ENUM_B		// 直接忽略
    #error "enum A != B"
#endif // A




//====================CONST===============================
const int constA = 1;
const int constB = 10;




#if constA != constB		// 直接忽略
    #error "const A != B"
#endif // constA



//=======================DEFINE==============================
#define defineA 1
#define defineB 2


#if defineA != define		// OK
    #error "define A != B"
#endif // defineA



因为预处理基本上就是宏定义展开,对程序内容和结构并没有处理,所以并不知道某个常数值为多少,某个枚举值为多少,更不知道存在某个类,因而只能接受宏定义。

话说有没有某种方法可以在编译后判断程序里某个常数值的范围?


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章