Return structure without its impact

I have a structure in my program

struct secret_structure{ string a; string b; void *c; }; 

I have a list of such structures

 std::map<string name, secret_structure> my_map 

I need to write a function that returns a structure by matching it with a name.

 get_from_map(string name, secret_structure * struct) //Kind of function 

I have the following options:

  • Pass the pointer of the secret structure to the get_from_map function. The get_from_map structure fills the structure. I do not want to do this because the structure will be exposed.

  • I can have different functions to return different values ​​from a structure. Here the structure will not be displayed, but does not look clean.

Can you help me with any other option so that the structure itself is not shown.

+4
source share
4 answers

Instead of passing a structure, you can pass a descriptor containing a pointer to a real object:

 // public_interface.h struct MySecretStruct; // I don't want to publish what inside struct WhatYouCanSee { MySecretStruct *msp; // The "P"ointer to "IMPLE"mentation WhatYouCanSee(int a, double b); ~WhatYouCanSee(); WhatYouCanSee& operator=(const WhatYouCanSee&); WhatYouCanSee(const WhatYouCanSee&); void method1(); void method2(int x); }; 

These methods will be just wrappers for calling methods of a real object.

+8
source

What you want is the pimpl idiom.

Acne idiom

Basically, you declare a class that has an interface to the secret structure and contains a pointer to an instance of the secret structure. You can redirect the struct declaration without specifying implementation details. Then in the CPP file you get access to the secret structure. This can be provided in a header / binary format if you provide it to third parties.

+7
source

Then go back to json or xml or some other format.

or ASN.1 may be more compact

+1
source

You cannot do this (at least not with normal C ++), and I cannot think that this is a good reason. If your internal structure is not a way to publish your information, find the appropriate method / data type and define the conversion.

+1
source

Source: https://habr.com/ru/post/1492643/


All Articles