Newshot

C 的指定初始化器带来了具名参数

Translation(model translation, not the source's own text)

C 的指定初始化器为我们带来具名参数

在上一篇里我谈到了 C++ 那种“相对被削弱”的指定初始化器形式。这次我想展示一个用 C 全功能指定初始化器能做出的巧妙玩法。我最早是在 Ben Klemens 的书 21st Century C(2014)第 226–228 页看到这个模式的。(Godbolt。)


        struct IdealVolumeArgs {
  double atm;      // P
  double moles;    // n
  double kelvin;   // T
};
#define ideal_volume(...) ideal_volume_impl( \
  (struct IdealVolumeArgs){ \
    .atm=1, .moles=1, .kelvin=273.15, __VA_ARGS__ \
  })
double ideal_volume_impl(struct IdealVolumeArgs args) {
  // The ideal gas law: PV = nRT
  return args.moles * 0.082057366 * args.kelvin / args.atm;
}

int main() {
  printf("1 mole of gas at STP occupies %g L\n",
    ideal_volume());
  printf("1 mole of gas at 100°C occupies %g L\n",
    ideal_volume(.kelvin = 373.15));
  printf("2 moles of gas at 100°C occupies %g L\n",
    ideal_volume(.kelvin = 373.15, .moles = 2));
  printf("2 moles of gas at 0°C and 2 atm occupies %g L\n",
    ideal_volume(.moles = 2, .atm = 2));
}
      

这个惯用法给了我们具名的、可带默认值的参数,同时保留自然的函数调用语法。它依赖 C 的指定初始化器里两项 C++20 没有采纳的特性:

  • 它们可以以任意顺序出现:(struct IdealVolumeArgs){ .atm=1, .moles=2 } 与 (struct IdealVolumeArgs){ .moles=2, .atm=1 } 含义相同。
  • 同一个指派符可以出现多次,只有最后一个“生效”:(struct IdealVolumeArgs){ .atm=1, .moles=2, .atm=3 } 与 (struct IdealVolumeArgs){ .atm=3, .moles=2 } 含义相同。
第二条意味着我们依赖的东西,如果不是有意为之,就会是糟糕的风格。Clang 默认会发出 -Winitializer-overrides 诊断。GCC(在我看来更合理)只在 -Wextra 下才发出 -Woverride-init。

一旦某个函数使用了这个惯用法,往函数定义里新增一个具名参数就不再是 API 破坏!比如,我们可能决定让调用方自己提供理想气体常数 R 的值。我们只需往 Args 结构体里加一个新字段。所有旧的调用点仍然能正常编译,行为也保持不变。(这不是 API 破坏,但确实是 ABI 破坏:调用方无需重写,但确实需要针对新头文件重新编译。)


        struct IdealVolumeArgs {
  double atm;      // P
  double moles;    // n
  double R;        // R -- this new field changes ABI
  double kelvin;   // T
};
#define ideal_volume(...) ideal_volume_impl((struct IdealVolumeArgs){ \
  .atm=1, .moles=1, .R = 0.082057366, .kelvin=273.15, __VA_ARGS__ \
})
double ideal_volume_impl(struct IdealVolumeArgs args) {
  return args.moles * args.R * args.kelvin / args.atm;
}
      

如果你在写一族相关的函数,可以让整族共享这个 Args 结构体;比如我们可以往结构体里加一个 .liters 字段,把它改名为 IdealGasArgs,然后用这袋关键字参数定义一整族函数:


        #define ideal_pressure(...) ideal_pressure_impl((struct IdealGasArgs){ \
  .atm=NAN, .moles=1, .kelvin=273.15, .liters=1, __VA_ARGS__ })
#define ideal_amount(...) ideal_amount_impl((struct IdealGasArgs){ \
  .atm=1, .moles=NAN, .kelvin=273.15, .liters=1, __VA_ARGS__ })
#define ideal_temperature(...) ideal_temperature_impl((struct IdealGasArgs){ \
  .atm=1, .moles=1, .kelvin=NAN, .liters=1, __VA_ARGS__ })
      

你也可以在前面加上任意数量的非关键字参数:


        typedef struct { int cx, cy, r; } CircleArgs;
void sc_circle_impl(ScreenContext *, int opcode, CircleArgs);
#define sc_erase_circle(sc, ...) sc_circle_impl(sc, 0, (CircleArgs){__VA_ARGS__})
#define sc_draw_circle(sc, ...)  sc_circle_impl(sc, 1, (CircleArgs){__VA_ARGS__})
#define sc_fill_circle(sc, ...)  sc_circle_impl(sc, 2, (CircleArgs){__VA_ARGS__})
      

实际中的用法

你应该动手用这个模式替换掉所有普通的 C 代码吗?绝对不要。与直接写一个普通的、不带命名参数的函数相比,它既笨重又“讨巧”,比如


        double ideal_volume(double atm, double moles, double kelvin) {
  return moles * 0.082057366 * kelvin / atm;
}
      

而这几乎总是你需要的全部。不过,在 GitHub 上快速做一次正则搜索,还是能找到几处看起来确实在用的地方。我发现的第一处值得分享的用法是在 gab462/hof-flecs-raylib 中,它用这个模式来编写这样的调用:


        send_message(&globals.send_buf, msg, .from_id = globals.name);
      

我发现使用该模式的最知名项目是 EpicGames/raddebugger:

typedef struct UI_AnimParams UI_AnimParams; struct UI_AnimParams { F32 initial; F32 target; F32 rate; F32 epsilon; B32 reset; }; internal F32 ui_anim_(UI_Key key, UI_AnimParams *params); #define ui_anim(key, target_val, ...) ui_anim_((key), &(UI_AnimParams){.target = (target

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗