Last Update:
Refactoring with C++17 std::optional
Table of Contents
There are many situations where you need to express that something is “optional” - an object that might contain a value or not. You have several options to implement such case, but with C++17 there’s probably the most helpful way: std::optional.
For today I’ve prepared one refactoring case where you can learn how to apply this new C++17 feature.
Intro
Let’s dive into the code quickly.
There’s a function that takes ObjSelection representing for example current mouse selection. The function scans the selection and finds out the number of animating objects, if there any civil units and if there are any combat units.
The existing code looks like that:
class ObjSelection
{
public:
bool IsValid() const { return true; }
// more code...
};
bool CheckSelectionVer1(const ObjSelection &objList,
bool *pOutAnyCivilUnits,
bool *pOutAnyCombatUnits,
int *pOutNumAnimating);
As you can see above, there are mostly output parameters (in the form of raw pointers), and the function returns true/false to indicate success (for example the input selection might be invalid).
I’ll skip the implementation for now, but here’s an example code that calls this function:
ObjSelection sel;
bool anyCivilUnits { false };
bool anyCombatUnits {false};
int numAnimating { 0 };
if (CheckSelectionVer1(sel, &