Initialising c-style structs - c++

I have a header that defines c style structs that are to be passed over a boundary on a c++ DLL. This header and DLL will potentially be used by c++, java and c applications. I want to initialise these structs in someway that allows the user to specify a subset of the parameters, and the rest will be given defaults.
I was thinking of creating a series of initialise functions in the header, which would take a reference to the struct they will initialise along with parameters for all members that can be set. The "initialise" functions would use overloading (based on the struct reference passed in) to ensure the correct one was called. I also planned on using default parameters to set the defaults. The functions would have to be gobal i guess.
Is this a good approach? Is there a better alternative? thanks

You could add a function that returns a default initialized structure :
struct abc
{
int a;
float b;
char c;
};
abc GetDefaultAbc()
{
const abc def = { 1,2.0,3 };
return def;
};

Related

How to refer a struct member value within itself?

Say I have the following simple struct in C/C++:
struct Example {
int member_a;
int member_b;
}
Now, I have an object ex of it.
For the sake of redundancy and properly relating some members, I need to assign member_b using the value of member_a. Here, as I knew the name of this object, something like this worked for me:
struct Example ex = {
.member_a = 50,
.member_b = ex.member_a * 2 // Assigning member_b in terms of member_a.
}
The above assignment works as long as int member_a is kept above int member_b in the declaration of Example struct.
I have already tried using .member_b = member_a ... and .member_b = .member_a ..., both of which failed to identify the member_a in a struct object. .member_b = <same_object_name>.member_a only seems to work with the initial definition.
Note: This all has been tried on version C18
It was a way out in case of this single struct object, but what if I do not want to use object name or if in case I'm using anonymous (unnamed) struct object? Can something like pointers or some equivalent of this exists that is compatible with C for using the relation in an object (or better if possible in struct definition itself)? Even being able to call a value of member like .member_a within Example struct shall do.
Update: If C and C++ vary a lot, please focus on a C specific solution.
C/C++ are two completely different languages if they're used modernly where C++ can take advantage of classes and the this keyword. I would assume that you want to use structs in C++ for this exact question.
If you want to just have a direct relationship for example member b is twice member, then just set them equal in the original class so that it happens during compile time.
struct Example {
int member_a;
int member_b = 2 * member_a;
};
Otherwise you have to explicitly site which struct you are using when accessing ints within it. In this case a struct doesn't have any members that strictly pertain to it and the compiler doesn't know if there's going to be a value at member_a. If you wanted to use a class then you would just set it at anytime to itself, with a function or set statement.
class Bob {
public:
int member_a;
int member_b;
private:
int double_member_a(){
member_b = 2 * member_a;
return member_b
};
};
Bob bob;
bob.member_a = 1;
bob.member_b = bob.member_a; // or bob.doubleA();
Regardless of the method you would still be changing a struct or classes values depending on that exact instance of the object so you would always have to state which one, though if you were going through any x struct of class you would just put them into a vector and do a range based for loop and access one at anytime.

Is it possible to dynamically check if a string of text is a member inside of a given class in C++?

I am wondering if there is any way to check if a given class contains a given member, except that given member's name is supplied as an std::string. Here is an example of the situation I am in:
class MyClass {
public:
int a;
int b;
int c;
void Handle_Class(std::string prop) {
if (this->prop) { //pseudo code of what I want to accomplish
//do stuff
};
};
} my_class;
int main() {
my_class.Handle_Class("a");
};
I know Handle_Class is not the best name for a function like this, but it is basically supposed to check if the class has a member called prop.
I have no idea how to actually do this though. Essentially I am trying to dynamically check if a class has a given member.
I have a lot of experience in Lua, and you could easily accomplish this in Lua (although Lua is not object oriented, you could accomplish this using tables)
local my_table = {a = 123; b = 456; c = 789};
local function Handle_Table(prop)
if my_table[prop] then
print("property "..prop.." exists inside my_table!");
end
end
I would appreciate any help.
Thanks
There is also a means of doing this at compile-time with templates, you cannot specify a dynamic string at runtime for the check, but consider:
How to detect whether there is a specific member variable in class?

C++ Parameters Structure supporting strings and integers?

How can I do this way easier:
struct Parameters {
public:
int Parameter1;
std::string Parameter1;
int Parameter2;
std::string Parameter2;
}
Isn't there "var" in C++ like in .NET ? I need parameters to be able to be integers and strings.
You have the key word 'auto' in C++ but it's on C++0x and C++1x, it's the compiler which will decide the type and it can't change after the compilation.
You're probably looking for something like boost::variant: http://www.boost.org/doc/libs/1_56_0/doc/html/variant.html
You can use Union, but you will still need to know at compile time what type you are assigning. You can sort of hide this by using templates with implicit typing to assign values, but you will still have to know the appropriate type when reading the value. Not sure how useful that would be though.
You could also use polymorphism and your own (template) wrapper class in place of the built in types.
I suggest you factor out the common code and set up to use a factory.
Use of a Factory
The problem is that you don't know the type of the parameter until you parse the string. The best method is to keep everything as a string or create a Factory and use a base class. For more research, see "c++ factory design pattern example".
struct Base_Parameter
{
std::string& parameter_as_string;
virtual void extract_parameter(const std::string& parameter_string) = 0;
};
struct Int_Parameter : public Base_Parameter
{
int parameter_value;
void extract_parameter(const std::string& parameter_string)
{
std::istringstream param_stream(parameter_string);
param_stream >> parameter_value;
}
}
Your parameter "list" would be either a container of pointers to the base class (if the types are unknown) or you could have a container of the descendent struct:
struct Parameter_Container
{
std::vector<Int_Parameter> parameters;
};
As for the factory, the factory would be an object that could create parameter objects based on some criteria. It would return a pointer to the base class.
Note: Unless you are on a tightly constrained platform, such as an embedded system, don't worry about overlapping memory locations to save room.

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)
{ ... }

Determining whether a non-object variable is initialized in C++

So, let's say, in a class in C++, I have a variety of member variables. Structs, strings, ints, etc. etc. Could be anything. These variables can or cannot be set by the initialization of the object of this class. Given int a, float b, char c, sometimes all of them or none of them can be set. When they are set, they can be set to any possible value of the variable. I would like to find someway of setting, and determining whether or not a variable has been set without:
1) Lots of casting. I could always create a Data_Value decorator class that has a boolean, and template it to whatever the given variable is. This would require calling a_data_value.value and a_data_value.isInitialized.
2) Lots of extra Boolean variables. I'd rather not have bool a_initialized, bool b_initialized.
What I would really like to do is something like this:
Python add to a function dynamically
in C++, with any and all variables, including primitives. Tall order I know, and I'm fully expecting the pessimistic answer.
You're right. It's impossible to determine at runtime whether a primitive is "set". Some compilers will warn you for some cases of using uninitialized values, but this is not at all guaranteed.
I would use a nullable template. See http://www.codeproject.com/KB/mcpp/CNullable.aspx
Suppose you have
class Bob {
int a;
int b;
double c;
complex<double> d;
Bob () : a(), b(), c(), d() {}
};
When you create a new Bob, everything will be set to default (zero in this case).
There is no set or not set state for primitive types. They always hold some value.
If you want to rewrite Python in C++ you can.
You'd need an efficient unordered_map class keyed by string. The string would be the variable name.
Each variable value would be a class (call it a VARIANT, heh) that can hold any primitive value.
Then instead of a C++ struct you'd make your "struct" be an instance of your unordered_map aka dictionary.
If the variable name is found in the dictionary then it was set and you can return the value. If it isn't found it was never set.
If you plan to reference your dictionary keys by name from within C++ you will want to use the following for efficiency:
Instead of:
VARIANT v = dict["name"];
Use:
static const std::string name_key("name");
VARIANT v = dict[name_key];
That way instead of building a std::string containing "name" for the key lookup every time into the function, it will be done once.