mardi 3 avril 2018

writing Binary File template functions

I have made a few functions to write and read class to binary file.

The 1st writeElement function i want to just be called if the argument is a class.

Then i want to have the other functions for int, double, size_t in one function. There has to be a better way to do this, i shouldn't have to create a new function for all different types.

template <class T>
inline void writeElement(ostream& out, T target) { target.write(out); }
inline void writeElement(ostream& out, int target) { out.write((char*)&target, sizeof(int)); }
inline void writeElement(ostream& out, double target) { out.write((char*)&target, sizeof(double)); }
inline void writeElement(ostream& out, size_t target) { out.write((char*)&target, sizeof(size_t)); }
inline void writeElement(ostream& out, const string str)
{
    size_t size = str.size();
    writeElement(out, size);
    out.write(&str[0], size);
}
template <class T>
inline void writeElement(ostream& out, vector<T> vector)
{
    size_t size = vector.size();
    writeElement(out, size);

    for (auto &element : vector)
    {
        writeElement(out, element);
    }
}


class Header
{
public:
    string sig;
    double  version;

public:
    void read(istream& in)
    {
        readElement(in, sig);
        readElement(in, version);
    }

    void write(ostream& out)
    {
        writeElement(out, sig);
        writeElement(out, version);
    }
};

Aucun commentaire:

Enregistrer un commentaire