wimalopaan
wimalopaan

Reputation: 5472

Reading from stream to initialize a read-only variable

I'm looking for an alternative to the following code

void foo(std::istream& in) {
    /*const*/ std::string token;
    in >> token;
}

where the local variable token could be const. I could imagine the following solution with a IIFE, but that looks utterly complex:

void foo(std::istream& in) {
    const std::string token = [&]{
        std::string v;
        in >> v;
        return v;
    }();
}

Any simpler alternatives? (without calling other own helper functions).

Edit: there is no need to use the >>-op. I only want to read in a whitespace separated string from the stream.

Upvotes: 1

Views: 182

Answers (2)

Alex Guteniev
Alex Guteniev

Reputation: 13689

Just read into another variable:

void foo(std::istream& in) {
    std::string token_read;
    in >> token_read;
    const std::string token = std::move(token_read);
}

Upvotes: 1

L. F.
L. F.

Reputation: 20609

Unfortunately, what you are trying to do is not possible because of the limitations of the istream interface, which works with non-const references. The best way to "add const" to a variable after it is modified is to use a helper function (or lambda):

template <typename T, typename CharT, typename Traits>
T read_from(std::basic_istream<CharT, Traits>& is)
{
    T value;
    is >> value;
    return value;
}

And then rely on named return value optimization (NRVO) to eliminate the extra variable: (even if NRVO does not happen, the value is moved instead of copied)

const auto token = read_from<std::string>(in);

Upvotes: 2

Related Questions