gpt4 book ai didi

c - 停止 bool 的宏扩展

转载 作者:太空狗 更新时间:2023-10-29 17:09:12 27 4
gpt4 key购买 nike

通过宏实现函数是 bool 的噩梦。我已经为(通用)函数的头部和主体定义了宏。使用 bool 类型时,结果很奇怪。

我知道这是您通常为了可维护性而希望避免的东西 ~ 但在我的例子中,它是一组非常相似的回调函数和一个非常苛刻的缩写。

所以目标实际上是可维护性和可读性,尤其是代码一致性。

#include <stdio.h>
#include <stdbool.h>

#define FUN_H(TYPE) \
void fun_##TYPE( void )

#define FUN(TYPE) \
FUN_H(TYPE) { \
printf("Type is " #TYPE ".\n"); \
}

FUN_H(int);
FUN_H(bool);

FUN(int);
FUN(bool);

int main(void) {
fun_int();
fun_bool();
}

阅读代码,我希望输出“Type is int”。和“类型是 bool 值。”

实际上,要使代码编译(当前 gcc/clang)必须将最后一次调用更改为 fun__Bool(); 并将 header 更改为 FUN_H(_Bool); - - 如果你知道你的 C99,这实际上是有道理的,但会产生不连贯的代码。


可能的解决方案

直接使用_Bool类型

FUN_H(_Bool);
FUN(_Bool); // or FUN(bool);

int main(void) {
fun__Bool();
}

优点

  • 无足迹

缺点

  • 丑陋!
  • 两种方法定义相同的函数,但打印不同的输出

手动展开FUN()

#define FUN(TYPE) \
void fun_##TYPE( void ) { \
printf("Type is " #TYPE ".\n"); \
}

优点

  • 其他宏类型的通用解决方案

缺点

  • 不符合 DRY 标准

typedef 用于 _Bool

typedef _Bool mybool;

FUN_H(mybool);
FUN(mybool);

int main(void) {
fun_mybool();
}

优点

  • 保守

缺点

  • 需要特殊的类型名称

bool更改为typedef

#undef bool
typedef _Bool bool;

FUN_H(bool);
FUN(bool);

int main(void) {
fun_bool();
}

优点

  • 清洁

缺点

  • 可能会破坏一些神秘的东西

那么我应该做什么?

最佳答案

如果 bool 是一个宏,它是将 bool 扩展为 _Bool 的内部 FUN_H 宏调用。如果你丢失了内部的 FUN_H 宏并像这样直接编写 FUN :

#include <stdio.h>
#include <stdbool.h>

#define FUN_H(TYPE) \
void fun_##TYPE( void )

#define FUN(TYPE) \
void fun_##TYPE( void ) { \
printf("Type is " #TYPE ".\n"); \
}

FUN_H(int);
FUN_H(bool);

FUN(int);
FUN(bool);

int main(void) {
fun_int();
fun_bool();
}

然后您将按预期获得 fun_bool,即使 bool 是一个宏。

关于c - 停止 bool 的宏扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461060/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com