Using std::optional and std::variant in C++

Sohini Dhar
2 min readJun 30, 2021

--

Exploring std::optional and std::variant in C++

C++17 introduced two new functionalities with the new standard : std::optional and std::variant. While the former gives us the option that a method/variable can/cannot contain a value, the other gives the flexibility to have a method that can return different types of data. We can have variables of these types and also methods that have these properties.

Let me try to elaborate with the help of an example:

#include <iostream>
#include <optional>
/* This function can either return an integer value or return nothing */
std::optional<int32_t> parseStringContents(const std::string& str)
{
int32_t value = atoi(str.c_str());
if(value!=0)
{
return value; //return value parsed from string
}
return std::nullopt; //return nothing
}
int main()
{
//Positive Scenario
std::optional<int32_t> x = parseStringContents("45");
if(x)
{
std::cout << *x << "\n";
}
else
{
std::cout << " Contents of x is not an integer\n";
}
//Negative Scenario
std::optional<int32_t> y = parseStringContents("sd45");
if(!y)
{
std::cout << "Contents of y is not an integer\n";
}
else
{
std::cout << *y <<"\n";
}

return 0;
}

Output:

45
Contents of y is not an integer

This is a very simple example and maybe you will find better examples all over the internet. But this will explain what you can achieve with std::optional. In my live code, I have used std::optional with std::ostream object to point to files that could be read from and for which I could not read/open I can return the std::nullopt option.

Now, let's look into an example with std::variant. Also, let me tell you this is a type-safe union.

#include <iostream>
#include <variant>
int main()
{
std::variant<int, std::string> var{60}; //This variable can either hold an int or a string, currently it holds an int
if(var.index()==0)
{
std::cout << get<int>(var) << "\n";
}
var = "Hello World!"; //Assigning a string to var
if(var.index()==1)
{
std::cout << get<std::string>(var) << "\n";
}
//The next two lines will cause an error as var can store values of type int or std::string and not float
/*var = 67.90f;
std::cout << get<float>(var) <<"\n";*/
return 0;
}

Output:

60
Hello World!

Hope you like the examples and you try to explore these two functionalities even more with your live project or code. Please remember you need C++17 supported compiler to execute these programs! Let me know in case you have more questions.

Happy C++ Coding! Please follow, like, comment, share if you like this.

--

--

Sohini Dhar
Sohini Dhar

Written by Sohini Dhar

Programmer, Traveler, Adventurer!!!!

No responses yet