Dmitry Kozyrev
Dmitry Kozyrev

Reputation: 49

Dynamic variables for structure

I have a structure:

struct options {
    char *type;
    char *action;
} params;

'type' and 'action' arrive from user input, and this is required parameters. But, i want to geting optional parameters and record it to struct. How can i do this? Is this possible?

Upvotes: 1

Views: 89

Answers (2)

jwezorek
jwezorek

Reputation: 9535

In C++17 you can use std::optional for this sort of thing.

#include <optional>

struct optional_params {
    int color;
    float frobication_level;
} params;

struct options {
    const char* type;
    const char* action;
    std::optional<optional_params> extra;
};

void useOptions(const options& opts) {
    // ...
    if (opts.extra.has_value()) {
        auto [color, frob_lvl] = opts.extra.value();
        // ...
    }
}

options opts = { "foo","bar", optional_params{1, 42.0} };
useOptions(opts);

Upvotes: 0

jhill515
jhill515

Reputation: 943

C++ Way

Depending on the type(s) of the optional parameters, you might want to consider std::map or std::unordered_map with an appropriate template type (e.g., some sort of polymorphic base reference).

C Way

This gets a little tricky, but there are some design options. In short, you're going to have to default the optional parameters to some common type (e.g., char-strings), and have a struct pairing them appropriately. For example,

typedef struct{
  char  param[32];
  char* val;
} ParameterPair;

Upvotes: 2

Related Questions