如何重写以下宏以便它们实际遵循c ++约定? (在C ++中,我们更喜欢使用typedef
,const
和inline
函数。
这是宏。
#define UBYTE unsigned char
#define ULONG unsigned long
#define FALSE 0
#define COMPRESS_MAX_COM 0x70000000
#define COMPRESS_MAX_ORG (1024-COMPRESS_OVERRUN)
#define MAX_RAW_GROUP (16*MAX_RAW_ITEM)
#define U(X) ((ULONG) X)
如何将上述宏更改为c ++约定?
答案 0 :(得分:3)
对于类型,请使用typedef
或using
(C ++ 11)代替#define
,然后使用const
作为常量。这些函数可以在C ++ 11中定义为constexpr
。
typedef unsigned char UBYTE; // using UBYTE = unsigned char; // C++11
typedef unsigned long ULONG;
const unsigned int FALSE=0; // constexpr usigned int FALSE = 0; // C++11
const ULONG COMPRESS_MAX_COM=0x70000000;
const ULONG COMPRESS_MAX_ORG=(1024-COMPRESS_OVERRUN); // if COMPRESS_OVERRUN is const
const ULONG MAX_RAW_GROUP=(16*MAX_RAW_ITEM); // again if MAX_RAW_ITEM is a previously defined const
#define U(X) ((ULONG) X) // this can stay as it is
或
template <typename T>
ULONG U(const T& x)
{
return static_cast<ULONG>(x);
}
所以U(some type T)
将返回其T
类型参数的强制转换为ULONG。
答案 1 :(得分:0)
您应该考虑整数大小,尤其是在接口中使用这些定义时。
例如:
#include <stdint.h>
typedef uint8_t UBYTE; // using UBYTE = unsigned char; // C++11
typedef uint32_t ULONG;
const uint32_t FALSE=0; // constexpr unsigned int FALSE = 0; // C++11
@vsoftco给出的其他定义很棒:
const ULONG COMPRESS_MAX_COM=0x70000000;
const ULONG COMPRESS_MAX_ORG=(1024-COMPRESS_OVERRUN); // if COMPRESS_OVERRUN is const
const ULONG MAX_RAW_GROUP=(16*MAX_RAW_ITEM); // again if MAX_RAW_ITEM is a previously defined const
#define U(X) ((ULONG) X) // this can stay as it is