C++ howto use the same function twice with different name and different names for variables - c++

I have a function that commands a device. This device is available twice so I need the same functionality for two devices. Out of maintenance reasons I don't want to have to code the function twice (one for each device) because then I always need to apply changes twice.
The functions are the same in principle but are supposed to work on different variables. Is it possible to instantiate this function with kind of a "varying" name, similar to template but not with classes but names?
I try to provide an example. It should look something like this.
void function_x (int Var, double Vary, ...) {
int var3_x = getFunctionFromDatabase(var3_x);
double var2_x = getFunctionFromDatabase(var2_x);
// some operations
}
The functions are applied by two instances of a Device Handler class.
The variables var1_x, var2_x and var3_x are stored in a data pool as var1_1, var1_2, var2_1, ... the "same" variable but one for each device. One Controller commands the two devices via these variables and the data pool.
Is this possible somehow?
I hope that the problem got clear ;). This is my first question here :P.
Thanks in advance for any help.

Why not use an array? E.g.
var1[0], var1[1], etc.
Use an array element for each device that you manage.
You could do some trickery with macros, but I think the code will be more clear if you use arrays.
Even if the variables are in a library that you can't change, you could set up arrays of pointers to the original variables in an initialization function. E.g.:
var1[0] = &var1_0;
var1[1] = &var1_1;
Then, function_x becomes function and would accept a parameter for the device index.

You say they have different variables, in which case it would be a simple case of overloading the function. Your example implies that you want to get the function from a database in which case you would need to use function pointers. Another option is that you have 1 function and you pass a handle (or some such) to it (as well as your arguments) to identify which device it is.

Related

How to automatically initialize component parameters?

While doing a game engine that uses .lua files in order to read parameter values, I got stuck when I had to read these values and assign them to the parameters of each component in C++. I tried to investigate the way Unity does it, but I didn't find it (and I'm starting to doubt that Unity has to do it at all).
I want the parameters to be initialized automatically, without the user having to do the process of
myComponentParameter = readFromLuaFile("myParameterName")
for each one of the parameters.
My initial idea is to use the std::variant type, and storing an array of variants in order to read them automatically. My problems with this are:
First of all, I don't know how to know the type that std::variant is storing at the moment (tried with std::variant::type, but it didn't work for the template), in order to cast from the untyped .lua value to the C++ value. For reference, my component initialization looks like this:
bool init(luabridge::LuaRef parameterTable)
{
myIntParameter = readVariable<int>(parameterTable, "myIntParameter");
myStringParameter = readVariable<std::string>(parameterTable, "myStringParameter");
return true;
}
(readVariable function is already written in this question, in case you're curious)
The second problem is that the user would have to write std::get(myIntParameter); whenever they want to access to the value stored by the variant, and that sounds like something worse than making the user read the parameter value.
The third problem is that I can't create an array of std::variant<any type>, which is what I would like to do in order to automatically initialize the parameters.
Is there any good solution for this kind of situation where I want the init function to not be necessary, and the user doesn't need to manually set up the parameter values?
Thanks in advance.
Let's expand my comment. In a nutshell, you need to get from
"I have some things entered by the user in some file"
to:
"the client code can read the value without std::get"
…which roughly translates to:
"input validation was done, and values are ready for direct use."
…which implies you do not store your variables in variants.
In the end it is a design question. One module somewhere must have the knowledge of which variable names exist, and the type of each, and the valid values.
The input of that module will be unverified values.
The output of the module will probably be some regular c++ struct.
And the body of that module will likely have a bunch of those:
config.foo = readVariable<int>("foo");
config.bar = readVariable<std::string>("bar");
// you also want to validate values there - all ints may not be valid values for foo,
// maybe bar must follow some specific rules, etc
assuming somewhere else it was defined as:
struct Configuration {
int fooVariable;
std::string bar;
};
Where that module lives depends on your application. If all expected types are known, there is no reason to ever use a variant, just parse right away.
You would read to variants if some things do not make sense until later. For instance if you want to read configuration values that will be used by plugins, so you cannot make sense of them yet.
(actually even then simply re-parsing the file later, or just saving values as text for later parsing would work)

Using C++ Classes to handle commonly used parameters

My team works on an HTTP web server in C++. The codebase has aged over time, and has a widespread problem of 12+ parameters being passed to every function.
A fake example: We need to build a Car, but in order to do that, we have the following function:
MaybeBuildCar(engine_params, steering_params, interior_params, fuel_params, available_inventory, parts, &debug);
Someone on our team has proposed that we create a wrapper CarBuilder class whose constructor takes in the params and "stateful" objects like available_inventory, then has a separate function for BuildCar as follows:
CarBuilder car_builder(engine_params, steering_params, interior_params, fuel_params, available_inventory, &debug);
auto car = car_builder.BuildCar(parts);
Personally, I don't see much value in having a class with a single public function that is always called. We'll always need these parameters, and we'll always need the parts, so this just adds more steps to build the car. It could even add confusion, as now a user of CarBuilder must know to both construct it and call BuildCar.
Admittedly, this simplifies our helper functions within car_builder.cc, as they also require passing these params, but to me that's misusing what a class is for: maintaining state.
Is creating this CarBuilder a misuse of the class, or is simply cleaning up function signatures a valid use? Does anyone have any suggestions on how to tackle this problem?
Minimizing function parameters can be a blessing for heavily used functions in a performance-sensitive environment:
If you pass 6 references to a function, that is 6 pointer copies pushed to the stack;
If you pass a single CarBuilder, it is one "reference-that-contains-6-other-references".
It depends on your situation.
you could define a class that contains all parameters and in each function just passed this object.
struct CarComponent
{
public:
EngineParams engine_params;
SteeringParams steering_params;
InteriorParams interior_params;
FuelParams fuel_params;
AvailableInventory available_inventory
};
MaybeBuildCar(car_component);
other_function(car_component);
Advantage:
Function's signature is decoupled from changing members of the struct (CarComponent). easy to change.
Refactor all the parameters in each function with a specific object. it prevents repetition and it becomes easier to read the code.

Creating a "Publisher->Dispatcher->Subscriber" pattern event system?

Edit: TL;DR
I guess my main problem is I don't know how to store a list of functions that all take one argument, where the argument type is different between each function, but always extends from EventBase, for calling later.
i.e: EventChild extends from EventBase. A function with the signature
<void (EventChild&)>
will not fit into a variable of type
std::function<void(EventBase&)>
How do I store functions like this, knowing that a user shouldn't have to modify the class where they are stored each time they create a new event extending from our EventBase class?
Note: I had previously been told I could use a dynamic_cast to accomplish this. I have been trying to do exactly that, but it hasn't been working. I imagine for that to work I would have to use pointers somehow, but I am new enough to C++ that I'm not sure how to do it. Maybe that should be the starting point?
One of the problems with dynamic casting pointers I have been having is 'I can convert a pointer of type:
(Subbscriber*)(getDemoEvent(EventDemo&)
to type:
void(EventBase&)
or something along those lines. (not at my computer right now to try it)
This is obviously a problem limited to member functions, I assume.
I recently posted a question on here with the intention of solving an issue for a C++ Event system based on a "Publisher->Dispatcher->Subscriber" pattern. I don't know the exact name of this pattern, but I hear that it is a variant on the Observer pattern with an added "middle-man."
I have been trying to get this system to work for a while now and I am completely stuck. It was suggested in the comments of the previous question that for what I was trying to accomplish, my program layout is incorrect. This is very likely the case since I had been researching other event systems that were close to what I am after trying to modify them for use they were unintended for. So I figured I would describe what I am after, and ask the more general question of "How would you go about structuring and creating this?"
So here is my general idea of how the system should be laid out and how it should operate in a basic example:
Starting with the idea of 5 different files (plus headers and maybe some subclasses):
main.cpp
dispatcher.cpp
publisher.cpp
subscriber.cpp
eventbase.cpp
publishers and subscribers could be anything, and they only serve as an example here.
The first order of business would be to create an instance of our Dispatcher class.
Following that, we create instances of our publisher/subscriber classes. These 2 classes could be a part of the same file, different files, multiples of each, or not event be classes at all but simply free functions. For the sake of simplicity and testing, they are 2 separate classes that know nothing about each other.
When these 2 classes are created, they should be passed a reference or pointer to our dispatcher instance.
This is easy enough. Now let's get to how you should use the system.
A user of the system should be able to create a class that inherits from our EventBase class. Ideally, there should be no requirement on variables or functions to override from the base class.
Let's say we have created a new event class called EventDemo, with a public const char* demoString = "I am a Demo Event";.
From our subscriber class, we should be able to tell our dispatcher that we want to listen for and receive some events. The syntax for doing so should be as simple as possible.
Lets create a member function in our subscriber that looks like this:
void Subscriber::getDemoEvent(const EventDemo &ev) {
std::cout << ev.demoString;
}
Now we need a way to bind that member function to our dispatcher. We should probably do that in our constructor. Let's say that the reference to our dispatcher that we passed to our subscriber when we created it is just called 'dispatcher'.
The syntax for subscribing to an event should look something like this:
dispatcher->subscribe("EventToSubTo", &getDemoEvent);
Now since we are in a class trying to pass a member function, this probably isn't possible, but it would work for free functions.
For member functions we will probably need and override that looks like this:
dispatcher->subscribe("EventToSubTo", &Subscriber::getDemoEvent, this);
We use 'this' since we are inside the subscribers constructor. Otherwise, we could use a reference to our subscriber.
Notice that I am simply using a string (or const char* in c++ terms) as my "Event Key". This is on purpose, so that you could use the same event "type" for multiple events. I.E: EventDemo() can be sent to keys "Event1" and "Event2".
Now we need to send an event. This can be done anywhere we have a reference to our dispatcher. In this case, somewhere in our publisher class.
The syntax should look something like this to send our EventDemo:
dispatcher->emit("EventToSubTo", EventDemo());
Super simple. It's worth noting that we should be able to assign data to our event through it's constructor, or even template the event. Both of these cases are only valid if the event created by the user supports it.
In this case, the above code would look something like this:
dispatcher->emit("EventToSubTo", EventDemo(42));
or
dispatcher->emit("EventToSubTo", EventDemo<float>(3.14159f));
It would be up to the user to create a member function to retrieve the data.
OK, so, all of that should seem pretty simple, and in fact, it is, except for one small gotcha. There are already systems out there that store functions in a map with a type of .
And therein lies the problem...
We can store our listener functions, as long as they accept a type of EventBase as their argument. We would then have to type cast that argument to the type of event we are after. That's not overly difficult to do, but that's not really the point. The point is can it be better.
Another solution that was brought up before was the idea of having a separate map, or vector, for each type of event. That's not bad either, but would require the user to either modify the dispatcher class (which would be hard to do when this is a library), or somehow tell the dispatcher to "create this set of maps" at compile time. That would also make event templating a nightmare.
So, the overly generalized question: How do we do that?
That was probably a very long winded explanation for something seemingly simple, but maybe someone will come along not not know about it.
I am very interested to hear thoughts on this. The core idea is that I don't want the 2 communicators (publisher and subscriber) to have to know anything about each other (no pointers or references), but still be able to pass arbitrary data from one to the other. Most implementations I have seen (signals and slots) require that there be some reference to each other. Creating a "middle-man" interface feels much more flexible.
Thank you for your time.
For reference to my last question with code examples of what I have so far:
Store a function with arbitrary arguments and placeholders in a class and call it later
I have more samples I could post, but I think it's highly likely that the structure of the system will have to change. Waiting to hear thoughts!

Where should the user-defined parameters of a framework be ?

I am kind of a newbie and I am creating a framework to evolve objects in C++ with an evolutionary algorithm.
An evolutionary algorithm evolves objects and tests them to get the best solution (for example, evolve the weights neural network and test it on sample data, so that in the end you get a network which has a good accuracy, without having trained it).
My problem is that there are lots of parameters for the algorithm (type of selection/crossover/mutation, probabilities for each of them...) and since it is a framework, the user should be able to easily access and modify them.
CURRENT SOLUTION
For now, I created a header file parameters.h of this form:
// DON'T CHANGE THESE PARAMETERS
//mutation type
#define FLIP 1
#define ADD_CONNECTION 2
#define RM_CONNECTION 3
// USER DEFINED
static const int TYPE_OF_MUTATION = FLIP;
The user modifies the static variables TYPE_OF_MUTATION and then my mutation function tests what the value of TYPE_OF_MUTATION is and calls the right mutation function.
This works well, but it has a few drawbacks:
when I change a parameter in this header and then call "make", no change is taken into account, I have to call "make clean" then "make". From what I saw, it is not a problem in the makefile but it is how building works. Even if it did re-build when I change a parameter, it would mean re-compile the whole project as these parameters are used everywhere; it is definitely not efficient.
if you want to run the genetic algorithm several times with different parameters, you have to run it a first time then save the results, change the parameters then run it a second time etc.
OTHER POSSIBILITIES
I thought about taking these parameters as arguments of the top-level function. The problem is that the function would then take 20 arguments or so, it doesn't seem really readable...
What I mean about the top-level function is that for now, the evolutionary algorithm is run simply by doing this:
PopulationManager myPop;
myPop.evolveIt();
If I defined the parameters as arguments, we would have something like:
PopulationManager myPop;
myPop.evolveIt(20,10,5,FLIP,9,8,2,3,TOURNAMENT,0,23,4);
You can see how hellish it may be to always define parameters in the right order !
CONCLUSION
The frameworks I know make you build your algorithm yourself from pre-defined functions, but the user shouldn't have to go through all the code to change parameters one by one.
It may be useful to indicate that this framework will be used internally, for a definite set of projects.
Any input about the best way to define these parameters is welcome !
If the options do not change I usually use a struct for this:
enum class MutationType {
Flip,
AddConnection,
RemoveConnection
};
struct Options {
// Documentation for mutation_type.
MutationType mutation_type = MutationType::Flip;
// Documentation for integer option.
int integer_option = 10;
};
And then provide a constructor that takes these options.
Options options;
options.mutation_type = MutationType::AddConnection;
PopulationManager population(options);
C++11 makes this really easy, because it allows specifying defaults for the options, so a user only needs to set the options that need to be different from the default.
Also note that I used an enum for the options, this ensures that the user can only use correct values.
This is a classic example of polymorphism. In your proposed implementation you're doing a switch on constant to decide which polymorphic mutation algorithm you will choose to decide how to mutate the parameter. In C++, the corresponding mechanisms are templates (static polymorphism) or virtual functions (dynamic polymorphism) to select the appropriate mutating algorithm to apply to the parameter.
The templates way has the advantage that everything is resolvable at compile time and the resulting mutating algorithm could be inlined entirely, depending on the implementation. What you give up is the ability to dynamically select parameter mutation algorithms at runtime.
The virtual function way has the advantage that you can defer the choice of mutation algorithm until runtime, allowing this to vary based on input from the user or whatnot. The disadvantage is that the mutation algorithm can no longer be inlined and you pay the cost of a virtual function call (an extra level of indirection) when you mutate the parameter.
If you want to see a real example of how "algorithmic mutation" can work, look at evolve.cpp in my Iterated Dynamics repository on github. This is C code converted to C++ so it is neither using templates nor using virtual functions. Instead it uses function pointers and a switch-on-constant to select the appropriate code. However, the idea is the same.
My recommendation would be to see if you can use static polymorphism (templates) first. From your initial description you were fixing the mutation at compile-time anyway, so you're not giving anything up.
If that was just a prototyping phase and you intended to support switching of mutation algorithms at runtime, then look at virtual functions. As the other answer recommended, please shun C-style coding like #define constants and instead use proper enums.
To solve the "long parameter list smell", the idea of packing all the parameters into a structure is a good one. You can achieve more readability on top of that by using the builder pattern to build up the structure of parameters in a more readable way than just assigning a bunch of values into a struct. In this blog post, I applied the builder pattern to the resource description structures in Direct3D. That allowed me to more directly express these "bags of data" with reasonable defaults and directly reveal my intent to override or replace default values with special values when necessary.

Lua: how to verify that a table contains a specific function

I'm developing a module that returns a table full of functions based on the arguments that are passed in. Specifically, the module returns a set of data transformation rules (functions) that need to be applied to a data set depending on which customer is sending it.
I decided to decouple my rule library (biz logic) from the code that decides which of the rules should be applied (config logic).
Here's the unit test I'm writing to verify that the ruleBuilder is adding the correct rule (function) based on one of my scenarios:
ruleBuilder = require("ruleBuilder")
ruleLibrary = require("ruleLibrary")
local rules = ruleBuilder.assembleRules("Customer1231")
assert(rules[1] == ruleLibrary.missingSSNRule)
Is this the correct way to do that verification? Will this work even if the ruleLibrary.missingSSNRule function has references to several other functions via a closure or parameter?
To verify that a table contains a particular function you may use the fact that keys in Lua tables can be anything (including functions). In your assembleRules code you can write something like this:
function assembleRules(...)
...
return {
[someOtherCoolModule.coolFunction] = someOtherCoolModule.coolFunction,
[yetAnotherModule.anotherFunction] = yetAnotherModule.anotherFunction,
}
end
Then later you can simply check if the key exists:
local rules = ruleBuilder.assembleRules("somedata")
assert(rules[someOtherCoolModule.coolFunction])
On the assumption that the return value of ruleBuilder.assembleRules is supposed to somehow know to put someOtherCoolModule.coolFunction in the 0-th index (note: Lua uses 1-based indices. Don't use 0 as an index) of its return value, then yes.
Will this work even if someOtherCoolModule.coolFunction is a closure?
All functions in Lua are closures. However, I'm going to assume that you mean that ruleBuilder.assembleRules is going to take someOtherCoolModule.coolFunction and build a new function around it.
A function is equal to itself. But it is only equal to itself. Just like two tables are only equal if they are the same table object, two functions are only equal if they are the same function. Functions are not equal to a different instantiation of the same function, nor is it equal to any other function. Here are examples of this.