mardi 5 avril 2016

Define forward declared nested struct / class / enum in another file for neatness

Are there any good methods of separating a nested data type definition from the container and into another file?

I have a class with multiple nested structs/class enums defined within a header which can be quite long.

MyClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_
#include <stdint.h>

namespace my_namespace{

class MyClass {

public:

  enum class NestedEnumClass {
    VALUE1, VALUE2, VALUE3
  };

  struct NestedStruct {
    float a;
    float b;
    uint_fast16_t c;
  };

  struct SomeOtherNestedStruct {
    float a;
    float b;
    uint_fast16_t c;
  };

  struct AnotherNestedStruct {
    float a;
    float b;
    uint_fast16_t c;
  };

private:
  struct CombinedStruct {
    NestedStruct a;
    NestedStruct b;
    NestedStruct c;
    AnotherNestedStruct d;
    NestedEnumClass e;
  };

  uint8_t pin;
  CombinedStruct data_;

public:
  MyClass();
  NestedEnumClass someMethod(NestedStruct nestedStruct);

}; // MyClass class.

} // my_namespace namespace.

#endif /* MYCLASS_H_ */

In order to make the header shorter/neater, I was initially thinking of forward declaring the data types in the MyClass definition header file and defining the data types in a separate source that includes the header file.

However, the compiler rightly complains about an incomplete type when I try to instantiate any of the data types.

I suppose I could include it in-line, but it seems horrible:
MyClass_DataTypes.inc

public:
enum class NestedEnumClass {
    VALUE1, VALUE2, VALUE3
  };

struct NestedStruct{
  float a;
  float b;
  uint_fast16_t c;
};


struct SomeOtherNestedStruct {
  float a;
  float b;
  uint_fast16_t c;
};

struct AnotherNestedStruct {
    float a;
    float b;
    uint_fast16_t c;
  };

private:
struct CombinedStruct {
  NestedStruct a;
  NestedStruct b;
  NestedStruct c;
  AnotherNestedStruct d;
  NestedEnumClass e;
};

MyClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_
#include <stdint.h>


namespace my_namespace{

class MyClass {

#include "MyClass_DataTypes.inc" // In-line include.

private:

  uint8_t pin;
  CombinedStruct data_;

public:
  MyClass(){};
  NestedEnumClass someMethod(NestedStruct nestedStruct);

}; // MyClass class.

} // my_namespace namespace.

#endif /* MYCLASS_H_ */

Also, my IDE (Eclipse) is not clever enough to find look at the include for on the fly code checking, so I would need to forward declare them in the class definition even though it compiles just fine without them.

Aucun commentaire:

Enregistrer un commentaire