I needed a class with more information than optionals give, I need to know why the optional is not valid in error states. I used a Boost variant for this. Since this will be wrapping almost all of my return values, I need to know if it's as fast as possible (i.e. did I do move semantics and all that jazz properly?).
template<typename T>
class Result
{
public:
Result(const std::string& errorString) {
contents = errorString;
}
Result(T&& value) {
contents = std::forward<T>(value);
}
operator bool() {
//is the active value our T
return contents.which() == 0;
}
T unwrap() {
return boost::get<T>(contents);
}
std::string unwrapErr() {
return boost::get<std::string>(contents);
}
private:
boost::variant<T, std::string> contents;
};
Example use
Result<std::vector<int>> foo()
{
if(success)
return Result<std::vector<int>>({1,2,3});
else
return Result<std::vector<int>>("failure reason");
}
if(auto vec = foo())
vec.unwrap() //do stuff to contained value
else
std::cout << vec.unwrapErr();