Skip to content

Commit

Permalink
2983: Add stream operators for result types
Browse files Browse the repository at this point in the history
  • Loading branch information
kduske committed Jul 14, 2020
1 parent a8a9511 commit 01445c2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/kdl/include/kdl/result.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "kdl/result_forward.h"

#include <functional> // for std::ref
#include <iosfwd> // users must include <ostream> to use stream operators
#include <optional>
#include <variant>

Expand Down Expand Up @@ -238,6 +239,11 @@ namespace kdl {
friend bool operator!=(const result& lhs, const result& rhs) {
return !(lhs == rhs);
}

friend std::ostream& operator<<(std::ostream& str, const result& result_) {
std::visit([&](const auto& v){ str << v; }, result_.m_value);
return str;
}
};

/**
Expand Down Expand Up @@ -444,6 +450,11 @@ namespace kdl {
friend bool operator!=(const result& lhs, const result& rhs) {
return !(lhs == rhs);
}

friend std::ostream& operator<<(std::ostream& str, const result& result_) {
std::visit([&](const auto& v){ str << v; }, result_.m_value);
return str;
}
};

/**
Expand Down Expand Up @@ -631,6 +642,13 @@ namespace kdl {
friend bool operator!=(const result& lhs, const result& rhs) {
return !(lhs == rhs);
}

friend std::ostream& operator<<(std::ostream& str, const result& result_) {
if (result_.m_error.has_value()) {
std::visit([&](const auto& v){ str << v; }, result_.m_error.value());
}
return str;
}
};

/**
Expand Down Expand Up @@ -821,6 +839,13 @@ namespace kdl {
friend bool operator!=(const result& lhs, const result& rhs) {
return !(lhs == rhs);
}

friend std::ostream& operator<<(std::ostream& str, const result& result_) {
if (result_.m_value.has_value()) {
std::visit([&](const auto& v){ str << v; }, result_.m_value.value());
}
return str;
}
};


Expand Down
16 changes: 16 additions & 0 deletions lib/kdl/test/src/result_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "kdl/overload.h"
#include "kdl/result.h"

#include <iostream>
#include <string>

namespace kdl {
Expand All @@ -36,6 +37,16 @@ namespace kdl {
return true;
}

inline std::ostream& operator<<(std::ostream& str, const Error1&) {
str << "Error1";
return str;
}

inline std::ostream& operator<<(std::ostream& str, const Error2&) {
str << "Error2";
return str;
}

struct Counter {
std::size_t copies = 0u;
std::size_t moves = 0u;
Expand All @@ -62,6 +73,11 @@ namespace kdl {
return *this;
}
};

inline std::ostream& operator<<(std::ostream& str, const Counter&) {
str << "Counter";
return str;
}

/**
* Tests construction of a successful result.
Expand Down

0 comments on commit 01445c2

Please sign in to comment.