Tutorial :Implementing something like std::vector.back()



Question:

I would like to implement something like this because my application is divided into scenes and this gets sort of messy:

glEngine.scene[glEngine.current.currentScene].layer[glEngine.scene[glEngine.current.currentScene].currentLayer].Shapes.push_back(CGlShape());  

instead I'd want to be able to do something like this:

glEngine.Scene().layer[glEngine.Scene().currentLayer].Shapes.push_back(CGlShape());  

How could I make a function like this?

Thanks


Solution:1

We have no idea what your classes are, but just make a function:

struct glEngine  {      // ...        scene_type& Scene()      {          return scene[current.currentScene];      }  };  

You can also do this for Scene, returning the current layer:

struct scene_type  {      // ...        layer_type& Layer()      {          return layer[current.currentScene];      }  };  

Giving:

glEngine.Scene().Layer().Shapes.push_back(CGlShape());  

You might also consider splitting the line up merely for the sake of readability:

scene_type& scene = glEngine.Scene();  layer_type& layer = scene.Layer();    layer.Shapes.push_back(CGlShape());  

Lastly, the naming convention seems a bit weird, maybe rename the Scene and Layer functions to current_scene and current_layer.


Solution:2

Use typedef to simplify cumbersome expressions! Typedef is for that.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »