expected (C++)
https://boostorg.github.io/outcome/alternatives/expected.html
So we have a variation of this internally inside NVIDIA, but the basic idea is the same.
I need to spend some time to understand.
Very similar to optional (C++) actually.
#include <iostream>
#include <boost/expected/expected.hpp> // Assuming boost::expected is available in your boost version
// Function that can either succeed or fail, returning boost::expected
boost::expected<int, std::string> divide(int a, int b) {
if (b == 0) {
return boost::make_unexpected("Division by zero error"); // Return an error string
} else {
return a / b; // Return the result if successful
}
}
int main() {
// Call the divide function with valid arguments
auto result = divide(10, 2);
// Check if the result is valid
if (result) {
std::cout << "Division successful: " << *result << std::endl; // Dereference the expected to get the value
} else {
std::cout << "Error: " << result.error() << std::endl; // Print the error
}
// Call the divide function with invalid arguments
auto result2 = divide(10, 0);
// Check if the result is valid
if (result2) {
std::cout << "Division successful: " << *result2 << std::endl;
} else {
std::cout << "Error: " << result2.error() << std::endl;
}
return 0;
}