Note that there are some explanatory texts on larger screens.

plurals
  1. POPattern for storing multiple types of struct in a C++ std::<vector> container
    primarykey
    data
    text
    <p>I have a data structure which represents a train, which can be made up of many types of car, for example the train engines, a grain car, a passenger car, and so on:</p> <pre><code>struct TrainCar { // ... Color color; std::string registration_number; unsigned long destination_id; } struct PowerCar : TrainCar { // ... const RealPowerCar &amp;engine; } struct CargoCar : TrainCar { // ... const RealCargoCar &amp;cargo; bool full; } std::vector&lt;TrainCar*&gt; cars; cars.push_back(new TrainCar(...)); cars.push_back(new TrainCar(...)); cars.push_back(new CargoCar(...)); cars.push_back(new CargoCar(...)); cars.push_back(new CargoCar(...)); </code></pre> <p>An algorithm will iterate through the cars in the train, and decide how to route/shunt each car (whether to keep it in the train, move it to another point in the train, remove it from the train). This code looks like:</p> <pre><code>std::vector&lt;TrainCar*&gt;::iterator it = cars.begin(); for (; it != cars.end(); ++it) { PowerCar *pc = dynamic_cast&lt;PowerCar*&gt;(*it); CargoCar *cc = dynamic_cast&lt;CargoCar*&gt;(*it); if (pc) { // Apply some PowerCar routing specific logic here if (start_of_train) { // Add to some other data structure } else if (end_of_train &amp;&amp; previous_car_is_also_a_powercar) { // Add to some other data structure, remove from another one, check if something else... } else { // ... } } else if (cc) { // Apply some CargoCar routing specific logic here // Many business logic cases here } } </code></pre> <p>I am unsure whether this pattern (with the dynamic_casts, and chain of if statements) is the best way to process the list of simple structs of varying types. The use of dynamic_cast seems incorrect.</p> <p>One option would be to move the routing logic to the structs (so like (*it)->route(is_start_of_car, &amp;some_other_data_structure...)), however I'd like to keep the routing logic together if possible.</p> <p>Is there a better way of iterating through different types of simple struct (with no methods)?, or do I keep the dynamic_cast approach?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload