【问题标题】:Is there a way to check if a member exists in a struct? [duplicate]有没有办法检查结构中是否存在成员? [复制]
【发布时间】:2012-06-30 05:48:43
【问题描述】:

可能重复:
How to detect whether there is a specific member variable in class?

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

【问题讨论】:

  • 见这个:stackoverflow.com/questions/257288/…。这是同一个概念。
  • SFINAE 是否可以在 g++ 以外的编译器中工作?
  • 结构如何“可选地”包含成员?
  • 非常感谢,这很有帮助。 @DanF:正如我所写:我想编写一个可与​​库的多个版本一起使用的附加组件。在某些版本中,该结构已表示成员在其他版本中没有。就是这样。
  • @con-f-use 这听起来像是在编译时确定的,不是吗?

标签: c++ struct member


【解决方案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;
   }
};

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多