std::optional
is a great choice for class members that may or may not have a value. Here's an example of how you can use it:
#include <optional>
#include <string>
class Player {
public:
Player(const std::string& name) : name(name){}
void set_level(int level) {
this->level = level;
}
std::optional<int> get_level() const {
return level;
}
private:
std::string name;
std::optional<int> level;
};
In this example, the Player
class has a name
member which is always present, and a level
member which is optional. The level
member is not initialized in the constructor, so it starts off empty.
The set_level
function sets the level
member to a specific value, making it non-empty.
The get_level
function returns the level
member. If level
has been set, it will return an std::optional
containing the level value. If level
has not been set, it will return an empty std::optional
.
Here's how you might use this class:
#include <optional>
#include <string>
#include <iostream>
class Player {/*...*/}
int main() {
Player player("Hero");
if (player.get_level()) {
std::cout << "Player level: "
<< *player.get_level() << std::endl;
} else {
std::cout << "Player level not set"
<< std::endl;
}
player.set_level(5);
if (player.get_level()) {
std::cout << "Player level: "
<< *player.get_level() << std::endl;
} else {
std::cout << "Player level not set";
}
}
This will output:
Player level not set
Player level: 5
Using std::optional
for class members is a safe and expressive way to handle values that may not be present. It clearly separates the "value not set" state from any possible value the member could have, including default-constructed values.
Answers to questions are automatically generated and may not have been reviewed.
std::optional
A comprehensive guide to using std::optional
to represent values that may or may not be present.