C++ funcional – std::optional

Algumas vezes, desejamos escrever funções que não retornam, necessariamente, um resultado. Nesses casos, podemos usar o contêiner
std::optional. Trata-se de uma alternativa boa para valores mágicos e exceções.

#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;
	}
}

Esta abordagem torna o código mais claro, expressando claramente a intenção. Não acha?

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:

The example which motivated this post comes from the excellent book Designing Distributed Systems by Brendan Burns (co-founder of the...
Um de nossos objetivos, nesse momento, é  melhorar a comunicação, compartilhando a visão do nosso fluxo de trabalho com a...
Nesse ano, palestrei na APIX sobre microsserviços. Abaixo, registro em vídeo feito pela organização do evento. Comentários? Feedback?
In the previous post, I mentioned Mario Fusco who wrote a blog post series questioning the way Java developers are...
Most of my client’s applications code is for parsing, caching, storing, aggregating, protecting and sharing data! It is not the...
In this post, I will help you to set up your first RavenDB cluster. To be honest, it is not...