-
Notifications
You must be signed in to change notification settings - Fork 0
Optional
DryPerspective edited this page Sep 19, 2023
·
1 revision
A dp::optional, copying std::optional is a type which either contains a value or does not. It maintains a well-defined state in both situations, performs no heap allocation, and does not construct the held object until it needs to. Helper instance dp::nullopt can be used to represent an empty optional.
Copy operations on a dp::optional maintain the strong exception guarantee. Optionals may not contain reference types, or instances of dp::nullopt_t
| operator* operator-> |
Access held value, without checking |
| operator bool has_value |
Check if the optional holds a value |
| value | Returns the held value, with checking |
| value_or | Returns the held value if there is one, and the parameter if not |
| swap | Swaps the values and statuses of two optionals |
| reset | Destroys any held value |
| operator== operator!= operator< operator<= operator> operator>= |
Compares the held values of two optionals |
| make_optional | Creates an optional object |
#include "cpp98/optional.h"
dp::optional<std::string> get_name(){
DB_query.add("SELECT [Name] FROM Foo WHERE Bar");
DB_query.open();
if(DB_query.empty()) return dp::nullopt; //Return an empty optional to signify that the name was not found
else return DB_query.get_value();
}
int main(){
dp::optional<std::string> name = get_name();
Print("The name in the database is " + name.value_or("not found")); //Prints the name if we got it from the function, or "not found" if not.
}