HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Directly initialize variable from std::istream

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stddirectlyfromvariableistreaminitialize

Problem

For some time it has been bothering me that there is apparently no way to directly initialize variables from input streams (something like `int i

  • There are serious performance implications



  • There are corner cases where this will not work or even worse produce silent errors.



  • I've overlooked any standard functions/classes that already implement that functionality.

Solution

There are corner cases where this will not work or even worse produce silent errors.

The function as it is, depends on the client to check for errors on the stream (either by calling std::cin.exceptions(std::ifstream::failbit); or by checking the stream state, after the call to get).

Ideally, I would want to write:

if(auto a = get(std::cin))
    // use a here


Maybe you could add something like this to your solution:

template
boost::optional get_optional(std::istream& in){
    T tmp;
    in >> tmp;
    return (in) ?
        boost::optional{ std::move(tmp) } :
        boost::optional{};
}

Code Snippets

if(auto a = get<int>(std::cin))
    // use a here
template<class T>
boost::optional<T> get_optional(std::istream& in){
    T tmp;
    in >> tmp;
    return (in) ?
        boost::optional<T>{ std::move(tmp) } :
        boost::optional<T>{};
}

Context

StackExchange Code Review Q#86238, answer score: 4

Revisions (0)

No revisions yet.