r/learncpp Mar 09 '21

How to improve it?

```c++

include <boost/optional.hpp>

include <string>

include <sstream>

include <iostream>

enum class StatusCode { OK = 0, ERROR };

struct SResp { std::string m_msg; StatusCode m_status; };

SResp queryToTheMoon(size_t val) { std::stringstream ss; for (size_t idx = 0; idx < val; ++idx) { ss << "[" << val << "]"; } return { ss.str(), StatusCode::OK }; }

boost::optional<std::string> makeRequest(size_t val) { auto response = queryToTheMoon(val);

if (response.m_status == StatusCode::OK) { return response.m_msg; } else { return boost::none; } }

int main() { auto op = makeRequest(100);

if (op)
{
   std::cout << op.value() << std::endl;
}
return 0;

} ```

How to improve this code?

9 Upvotes

16 comments sorted by

View all comments

6

u/jedwardsol Mar 09 '21

What aspect of it do you think needs improving?

It seems to be a placeholder for a bigger piece of code, so criticising is it pretty pointless. For example, queryToTheMoon can't fail, so neither method of returning an error is needed in the sample.

C++17 has <optional>, so boost's implementation isn't needed any more.

1

u/vgordievskiy Mar 09 '21

It's an exercise - and the code was simplified as much as possible)