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:

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:

No último post desta série, tratamos da “Lei do Retorno Acelerado”. Sabemos que negócios digitais tem crescimento potencialmente exponencial. Neste...
Empresas, famílias e grupos de amigos mudam. Entretanto, uma coisa permanece constante: o fato de que todos percebemos a vida...
Inspecting the code repository of a client, I found something like this: var customer = new { Id = default(int),...
Some years ago, Alistair Cockburn proposed this interesting pattern. Quoting his words, the primary intent is: Allow an application to...
Nos últimos dois posts demonstrei como as alocações podem implicar em penalidades de performance. Nesse post, parto, novamente, de código...
Tentando ser “Júnior” Minha carreira como amador remunerado em programação começou em 1992. Eu tinha quase 13 anos e era...