简体   繁体   中英

Initialise C-structs in C++

I am creating a bunch of C structs so i can encapsulate data to be passed over a dll c interface. The structs have many members, and I want them to have defaults, so that they can be created with only a few members specified.

As I understand it, the structs need to remain c-style, so can't contain constructors. Whats the best way to create them? I was thinking a factory?

struct Foo {
    static Foo make_default ();
};

A factory is overkill. You use it when you want to create instances of a given interface, but the runtime type of the implementation isn't statically known at the site of creation.

The C-Structs can still have member functions. Problems will, however, arise if you start using virtual functions as this necessitates a virtual table somewhere in the struct's memory. Normal member functions (such as a constructor) don't actually add any size to the struct. You can then pass the struct to the DLL with no problems.

I would use a constructor class:

struct Foo { ... };
class MakeFoo
{
   Foo x;
public:
   MakeFoo(<Required-Members>)
   {
     <Initalize Required Members in x>
     <Initalize Members with default values in x>
   }

   MakeFoo& optionalMember1(T v)
   {
      x.optionalMember1 = v;
   }

   // .. for the rest option members;

   operator Foo() const 
   {
     return x;
   }
};

This allows to arbitrary set members of the struct in expression:

processFoo(MakeFoo(1,2,3).optionalMember3(5));

I have an easy idea, here is how:

Make the structure, just like you normally would, and create a simple function that initializes it:

struct Foo{...};

void Default(Foo &obj) {
    // ... do the initialization here
}

If you have multiple structures, you are allowed in C++ to overload the function, so you can have many functions called 'default', each initializing its own type, for example:

struct Foo { //... };
struct Bar { //... };

void Default(Foo &obj) {...}
void Default(Bar &obj) {...}

The C++ compiler will know when to call the first or the second overload based on the parameter. The & makes obj a reference to whatever parameter you give it, so any changes made to obj will be reflected to the variable you put as parameter.

Edit: I also have an idea for how to specify some parameters, you can do it by using default parameters. This is how it works:

For example you the following function; you can specify default values for parameters like this:

void Default (Foo &obj, int number_of_something = 0, int some_other_param = 10)
{ ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM