select sub-class 在编译时通过#define 实例化的最佳方法是什么

What is the best way to select sub-class to instantiate at compile time via #define

我目前有一个 IoT 小工具,它具有不同的显示子class,具体取决于我正在编译的硬件。有一个名为 Display 的基础 class,它有各种子 class,例如 D_oled32 和 D_oled64。在编译时,我通过#define 设置了一个构建标志,这样当我实例化 Display 对象时,它将选择指定的 subclass。我现在的方法确实有效,但 VSCode 对此感到困惑,我不知道是否有更优雅的方法。目前我这样做:

#if defined(MAX7219)
    #include "Displays/D_max7219.h"
    #define DISPLAY_CLASS D_max7219
#elif defined(EPD)
    #include "Displays/epdfeather.h"
    #define DISPLAY_CLASS D_epdfeather
#elif defined(OLED32)
    #include "Displays/D_oledy32.h"
    #define DISPLAY_CLASS D_oledy32
#elif defined(OLED64)
    #include "Displays/D_oledy64.h"
    #define DISPLAY_CLASS D_oledy64
#elif defined(CHA)
    #include "Displays/ledfeather.h"
    #define DISPLAY_CLASS D_ledfeather
#endif
Display *display;

然后在设置中我这样做:

    // setup the display object
    // display hardware is specified at compile time
    display = new DISPLAY_CLASS(config);    // DISPLAY_CLASS is SET in a #define at the top of this file

您不应“定义”类型,而应使用 using 为类型设置别名:

#if defined(MAX7219)
  #include "Displays/D_max7219.h"
  using DISPLAY_CLASS = D_max7219;
#elif defined(EPD)
  #include "Displays/epdfeather.h"
  using DISPLAY_CLASS = D_epdfeather;
#elif defined(OLED32)
  #include "Displays/D_oledy32.h"
  using DISPLAY_CLASS = D_oledy32;
#elif defined(OLED64)
  #include "Displays/D_oledy64.h"
  using DISPLAY_CLASS = D_oledy64;
#elif defined(CHA)
  #include "Displays/ledfeather.h"
  using DISPLAY_CLASS = D_ledfeather;
#endif
Display *display = new DISPLAY_CLASS(config);