C++ going functinonal – std::optional

Sometimes we want to write functions that may not always return a result. In these cases we can use the std::optional container. That’s a pretty good alternative to special magic values and exceptions.

#include <optional>
#include <string>
#include <sstream>
#include <iostream>

std::optional<int> TryParseInt(std::string input)
{
	std::stringstream parser(input);
	
	int result;
	parser >> result;
	
	if (parser.fail() || !parser.eof())
		return {};

	return result;
}

int main()
{
	std::cout << "nEnter a number: " << std::endl;

	std::string input;
	std::cin >> input;

	auto parseResult = TryParseInt(input);

	if (parseResult.has_value())
	{
		for (auto i = 0; i < parseResult; i ++)
		{
			std::cout << i << std::endl;
		}
	}
	else
	{
		std::cout << "Invalid number!" << std::endl;
	}
}

This approach make the code more readable, as the intent is expressed explicitly. Dont’t you think?

Compartilhe este insight:

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

Write code is not a simple task. It is easy to make mistakes that result in bad performance. The last...
The example which motivated this post comes from the excellent book Designing Distributed Systems by Brendan Burns (co-founder of the...
In the first post of this series, I explained how to produce an inverted index using C#. In the second...
Publicado originalmente em meu linkedin Se há algo que aprendi, tanto academicamente quanto empiricamente, é que a motivação é intrínseca...
Um servidor de identidades é um artefato de sofware que centraliza os dados de usuários, bem como o processo para...
In this post, I would like to share my first attempt to create a (still) elementary search library. The source...