有没有办法检查结构中是否存在成员

Is there a way to check if a member exists in a struct?

本文关键字:是否 存在 成员 结构 检查 有没有      更新时间:2023-10-16

可能的重复项:
如何检测类中是否存在特定成员变量?

我正在向C++库添加功能。派上用场的一件事是检查结构中是否存在某个成员(它的存在取决于库版本 - 不幸的是,库中没有"版本"参数)。

以下是我想做的简化示例:

struct options {
    int option1;
    std::string option2;
    float option3; // might be included or not
    options();
    void random_method();
}
options::options() {
    option1 = 1;
    option2 = "foo";
    if( EXISTS(option3) ) { // Pseudo-Code -> can I do that at all?
        option3 = 1.1;
    }
}

您可以在父结构中实现一个纯虚函数,并让子结构实现它。

struct Parent
{
  virtual bool has_option(OPTION) const = 0;
};
struct Car : public Parent
{
  bool has_option(OPTION op) const
  {
     bool result = false;
     if (op == MOON_ROOF)
     {
         result = true;
     }
     return result;
   }
};