#Extendible way to store item names for a dropdown list

5 messages · Page 1 of 1 (latest)

opaque yacht
#

In my program I have a base class which declares the interface for a 'point generator', a class which generates a number of coordinate pairs. There can be different kinds of point generators because they might use different approaches to compute the coordinates. To this end I have defined a pure virtual function virtual std::vector<std::pair<int, int>> generatePoints(int n, const double plot_width, const double plot_height) = 0; in a base class.

I can now make a UniformRandomGenerator which inherits from the base class and implements it's own specific generatePoints method, or a BestFitGenerator with some other implementation. The user is able to select which generator they want to use from a combobox /dropdown list in the GUI. At the moment I am storing the names of the various generators like this:

const char* node_generator_items[] = { "Uniform Random", "Best Fit"};

//Dear ImGui code for a combo box
if (ImGui::BeginCombo("Node Generator", nodecombo_preview_value,
                      tree_gen_flags))
{
 // some code which uses the node_generator_items above to make the combo box
}

additionally the generators are selected like this:

//Select node generator based on selection
std::unique_ptr<NodeGenerator> node_generator;
switch (nodegen_current_idx_) {
default:
    node_generator = std::make_unique<UniformGenerator>();
    break;
case 1:
    node_generator = std::make_unique<BestCandidateGenerator>();
    break;
};
auto points = node_generator->generatePoints(numberOfNodes_, plot_limits.X.Size(), plot_limits.Y.Size());

I am unpleased with this as if I want to extend the available generators in future, say adding some new kind of generator, the user then has to go into the file containing the GUI code and hardcode in the name of the new generator and also add an additional case.

What would be a better way to achieve this, which is less 'hard codey'?

livid auroraBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

tranquil raft
#
template <class Generator_type>
void add_generator(std::string name);

is probably as good as it gets.

#

You can then have an std::vector<std::string> to store the list of generator names (which add_generator adds an entry to) and an std::vector<std::unique_ptr<NodeGenerator>> node_generators; (which add_generator also adds an entry to).

#

And you replace the switch with node_generators[index].