Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating object with constant parameters from stream

Tags:

c++

let us assume I have a class with

#include <iostream>
using namespace std;

class Test{
    public:
        friend istream& operator >> (istream& input, Test& test){
            input >> test.dummy;
            return input;
        };
        friend ostream& operator << (ostream& output, Test& test){
            output << test.dummy << endl;
            return output;
        };
    private:
        const int dummy;
}

This does not work because dummy is constant. Is there a way to load from file and recreate an object with parameters which are constant?

like image 870
varantir Avatar asked Oct 15 '15 08:10

varantir


Video Answer


1 Answers

The "I really, really need this" way

Use const_cast. Usually you use it for objects that outside look like if they are constant, but internally they do need to update state every now and then. Using it for reading from stream is a little confusing, to say the least.

friend istream& operator >> (istream& input, Test& test){
    input >> const_cast<int&>(test.dummy);
    return input;
};

The recommended way

Ditch stream operator, use a factory function.

static Test fromStream(istream& input) {
    int dummy;
    input >> dummy;
    return Test(dummy);
}

The best way

Ditch const. Instead, pass your entire object as const if needed.

like image 139
gwiazdorrr Avatar answered Sep 18 '22 12:09

gwiazdorrr