specify allowed value range for boost::program_options value - c++

I want to set limits on value specified in command line. And it would be great if this range will be automatically printed within description like default value.
Also is is interesting if there is a way to create my own type and do specialization of po::value for my enum type.
For example
enum percent
{
percent0,
percent10,
percent20,
percent30,
percent40,
...
percent100
};
po::value<percent>() <-- gives compile time error
update
I would like to add information about allowed values to the value_semantic object, like it is done for the default value or for required flag.
I noticed that typed_value class is polymorphic and can be extended, so I want to create a new class
class range_int : public po::typed_value<int> {}
and later when iterating description options I can do dynamic_cast<> and check if value is range_int, but I don't like this solution because of cast is required for it, but there is no way to add virtual functions to the base interface.
The purpose of this is to extend program options. I need to write another description output function which will output program options in format that is easy to parse (for example XML). I also need to add range to some of the values, so I need this information be stored in program options.
Any suggestions?

You can try to use custom validator with a custom type to hold your information.
The example provided is self explanatory

Related

proto3 check if parameter is set

since in proto3 all parameters are optional when parameter is not set and message is deserialized then unset parameter holds default value. I can not find a way to check if the parameter has been set or not. Is there any way to find if parameter has been set similary as in proto2? I see that there is a method has_<param_name>() but it is private.
I don't think the distinction exists anymore in proto3. You are encouraged to have meaningful defaults.
But if you must, you can use a singular embedded message containing the value.
It seems after Protobuf 3.15.0 you could use hasField in C++ again:
According to the CHANGELOG:
Now Proto3 Oneof fields have "has" methods for checking their presence in
C++.
Building upon ramsay's answers, one thing that you can do if you have a real need for Null kind of value, is this:
import "google/protobuf/struct.proto";
message Test {
oneof value_or_null {
string value = 1;
google.protobuf.NullValue null = 2;
};
}
with the one of you will get the has_<param_name>() function back and you will be able to check if you have null or a value. Also this is a safer approach because you cannot set the two fields, the oneof implementation will make sure that potential previous field value get cleared and set the new one.
Do note however, that evolving oneof fields is trickier than evolving normal fields (you can see the potential problems here)
My recommendations
I would first make sure that there is a real need for Null and thus a real need for oneof.
I would try to make the default value of each field an invalid value in my business logic (eg: uint32 id with 0 value is invalid and I return an error)

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)

Generic Mutator/Accessor functions

Is there a way to create generic set/get functions in C++? I have a class with a large number of attributes but no functions (ok I should probably use a struct), and really don't want to write individual set and get functions for each data member. The functions I'm thinking of would be something like 'set_member( T variable ), where T could be anything, primitive types or user defined. I imagine perhaps you could create a struct with a struct as a member, then whenever you want to access a specific member of the member struct, you refer to it by the appropriate pointer. I've tried writing something to achieve this but no luck so far.
C++ has (as far as I know) no inbuilt way to autogenerate setter/getter functions.
You might be able to work some macro-magic (with all its pitfalls), otherwise your options are slim.
I can think of following alternatives:
Some IDEs generate get, set methods automatically for the data members of class. I am not sure if it is possible for C++ IDE. But I know that Eclipse IDE for Java does it. You may check once if Eclipse IDE for C++ has this facility.
You may write a short shell script or python script for automatically generating get, set method given a text file containing names and types of variables in each line.
By default all the members of struct are public. So use struct. Or if you decide to use class, then, put all the data members in public section. If you are not doing anything other than simple set, get, then, it might be ok to do so. However, debugging will be tedious in case if you encounter issues with changes in the data members.

Should I prefer a const function?

Assume I want to implement class A which must load its "configuration" from a file. And let's assume the "configuration" is a simple map<string, string>.
I can implement the A::LoadConfiguration in two different ways:
void A::LoadConfiguration(string filename)
map<string, string> A::LoadConfiguration(string filename) const
Should I prefer either of the two implementations, and why?
If you prefer the second version when the user wants to get info on a file they will base all their algorithms on the map. If you do the second version, meaning the implementation may be a map, but doesn't have to be, they can base their code around an API which does not have to change even if the internal implementation does.
Consider the situation where later you realize it is far more efficient to use an std array, for whatever reason, now every program using this code has to change many of it's algorithms. Using the first version the change to array can be handled internally and reflect no changes on the outside.
Now if you are planning to make multiple instances of the class you will definitely want to make it a static method because you don't want the file to load every time you call the constructor (especially if the file will not change).
Completely ignoring your suggestions, but this is probably how I would do it (not knowing all your constraints, so ignore me if it does not fit):
class A
{
public:
static A fromConfiguration( string fileName );
/* ... */
}
In most cases, the "configuration" of a class should be set at object creation, so forcing the user to provide it on construction is a good thing (instead of having to remember to do do the loading later).
namespace NeatStuff
{
map<string,string> loadSimpleConfiguration( string fileName );
}
If the configuration file format is really simple (and not specific to your class) you can move the actual loading out of the class.
Assuming other classes use the configuration later, I prefer option 1, and an additional GetConfigurationParameter public const method that gets the config value for a particular key. That lets me make other classes which can just ask for some parameter by name without ever caring that it's implemented as a map.
Another reason why I prefer option 1 is that loading a configuration should be distinct from returning it. If I see a name like LoadConfiguration, I assume that it loads the config from somewhere and sets the parameters in the class. I do not assume it returns some description of the configuration, which I'd instead expect from a method like GetConfiguration - but opinions on this will vary for different people of course.

Identifying methods with a specified Id in D

I want to have specific methods with a specific pattern recognized at compile time and registered along with a specified id trough mixins in a parent class.
ex.:
take a method 'X' from a class with a predetermined id:5, what I want is that, in a mixin in a parent class, method X will be registered as a delegate with its id to be called later on by its id.
What would be the best way to specify the Id considering I want the id to be of type int and only the specified methods to be registered?
should I (if it is even possible) do it with a custom annotation pretty much like the #property but with an argument, like:
#autoregister(id)
void method(...)
if it is possible to do it this way, an example or a link to the documentation on how to do it would be nice since I didn't find it in the documentation.
if it is not possible I'll use the function's signature as a string instead but I really want to do it with a numeric identifier instead of a possibly quite long string as much as possible.
Making custom annotations is not possible at the moment (but it will be in the future).
However, you can make your own method-naming convention that will allow you to do something similar to what you have described. I do not have time to think deeply how to accomplish this, but I would start with having a method like:
public void id30_doSomething(/* params */) {
// body
}
alias id30_doSomething doSomething;
// finally, lets do something with all these methods
// and generate mixin...
After this you could probably list all methods and find if their names match id([0-9]*)_.*, if so, then you generate mixin to register them in the parent...