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:

Neste post, compartilho mais algumas ideias que tenho adotado, com êxito, em meus projetos envolvendo Microsserviços e que podem ajudar...
Sempre fui péssimo jogando videogames. Aliás, esse é um dos motivos para eu ter começado a olhar computadores de outra...
Há alguns dias tive a oportunidade de falar sobre Inovação e Empreendedorismo com empresários da serra gaúcha. Nessa conversa, disponível...
As professionals, we should focus on developing great technical solutions. But, these solutions need to solve real problems. At the...
Uma dúvida comum e recorrente em minhas consultorias é “Como eu faço para manter a consistência de dados entre meus...
Qual deveria ser o resultado da execução desse código? using System; using System.Threading.Tasks; using static System.Console; using static System.IO.File; class...