C++之#和##符号的用法

#的用法是将宏参数转化为字符串
##的用法是将多个宏参数拼接在一起

#include <stdio.h>
#include <climit>
#define STR(s) #s
#define CON(a,b) a##e##b

int main()
{
    printf(STR(hello));         //输出字符串"hello"
    printf("%d\n",CON(2,3));    //2e3, 输出2000
    return 0;
}

注意当宏参数是另一个宏的时候,另一个宏将不会展开!只有当前宏会展开

#include <stdio.h>

#define STR(s) #s

int main()
{
    printf(STR(INT_MAX)); //INT_MAX是climit定义的宏,输出字符串"INT_MAX"
    return 0;
}

解决方法:加多一层中间转换宏,宏参数先行展开后,再作为当前宏的宏参数

#define _STR(s) #s
#define STR(s) _STR(s)

综合运用示例

#的用法是非常有用的,如可以直接我我们定义的枚举转化为字符串,从而不用再次定义这个枚举对应的字符串。

  • EventDefinition.cfg
#define EVENT_TABLE() \
    DEF_EVENT(kEvent_1) \
    DEF_EVENT(kEvent_2) \
    DEF_EVENT(kEvent_3) \
    DEF_EVENT(kEvent_4) \
    DEF_EVENT(kEvent_5) \
  • EventDef.h
#ifndef INCLUDE_EVENTDEF_H
#define INCLUDE_EVENTDEF_H

#include "EventDefinition.cfg"

enum class EventType : uint16_t {
#define DEF_EVENT(v) v,
  EVENT_TABLE()     //这里相当于定义了枚举类Eventype::kEvent_1~kEvent_5
#undef DEF_EVENT
};

//获取枚举转化的字符串接口
const char* EventStringOf(EventType c) {
    switch (c) {
#define DEF_EVENT(v) \
  case EventDataType::v:          \
    return #v;
      EVENT_TABLE()
#undef DEF_EVENT
      default:
        return "Unknown event";
    }

#endif  /INCLUDE_EVENTDEF_H

拓展

enum class枚举类

  • enum现在被称为不限范围的枚举型别
  • enum class是限定作用域枚举型别,他们仅在枚举型别内可见,且只能通过强制转换转换为其他型别。
  • 两种枚举都支持底层型别指定,enum class默认是int,enum没有默认底层型别,enum class可以前置声明, enum仅在指定默认底层型别的情况下可以前置声明
//用法
enum : 型别{}
enum class :型别{}

enum Color{Red, Blcak, Blue};
enum class Color:int16{Red, Blcak, Blue};

//前置声明
enum Color;         //错误
enum class Color;   //正确

参考:
https://blog.csdn.net/weixin_42817477/article/details/109029172

posted @ 2024-04-12 15:42  HL棣  阅读(28)  评论(0编辑  收藏  举报