宏的重写以遵循 C++ 约定

macro's rewrite to follow the c++ convention

本文关键字:C++ 约定 重写      更新时间:2023-10-16

如何重写下面的宏,使它们真正遵循c++约定?(在C++中,我们更喜欢使用typedefconstinline函数)
这是宏

#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++约定?

对类型使用typedefusing(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);
}

所以CCD_ 9将返回其类型为CCD_。

您应该考虑整数大小,尤其是在接口中使用这些定义的情况下。

例如:

#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