0

Possible Duplicate:
How to detect whether there is a specific member variable in class?

I'm adding features to a C++ library. A thing that'd come in handy was to check if a certain member exists in a struct (it exisits depending on the library version - unfortunately there is no "version" parameter in the library).

Here is a simplified example of what I'd like to do:

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;
    }
}
Community
  • 1
  • 1
con-f-use
  • 3,772
  • 5
  • 39
  • 60
  • 3
    See this: http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence/264088#264088. It's the same concept. – chris Jun 28 '12 at 16:41
  • Does SFINAE work in compilers other than g++? – con-f-use Jun 28 '12 at 16:51
  • How can a struct "optionally" include a member? – Dan F Jun 28 '12 at 17:12
  • Thanks a lot, that was helpful. @DanF : As I wrote: I want to write an addion that works with serveral versions of the library. In some version the struct has said member in others it does not. That's how. – con-f-use Jun 28 '12 at 17:25
  • @con-f-use That sounds like something that would be determined at compile-time, wouldn't it? – Dan F Jun 28 '12 at 17:33

1 Answers1

0

You could implement a pure virtual function in the parent structure and have the children implement it.

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;
   }
};
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154