Modern C++ idoms and recipes

meshell
2,330 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

std::variant

In the previous exercise we used std::optional to indicate failure. But how about a more detailed error message?

Enter template class std::variant. We could use std::variant to either hold a valid value or a detailed error.

DIY

Refactor function differentiate to have return type std::variant<double, std::string> and once again make the tests pass. The variant should either be a valid value or an error string.

Refactor the code to use std::variant
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <functional>
#include <sstream>
#include <string>
// symmetric difference quotient
double differentiate(std::function<double(double)> f, double h, double x)
{
return (f(x + h) - f(x - h)) / (2 * h);
}
std::string estimated_velocity(std::function<double(double)> distance, double time, double precision)
{
auto velocity = differentiate(distance, precision, time);
std::stringstream output;
output << "Estimated velocity after " << time << " seconds is " << velocity << " m/s.";
return output.str();
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content