0

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

我正在向 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;
    }
}
4

1 回答 1

0

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

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;
   }
};
于 2012-06-28T17:49:21.420 回答