简体   繁体   中英

How do I serialise a template class

I am performing some background maintenance to legacy code.

It involves replacing a deprecated library with the STL and boost whilst keeping the interface as similar as humanly possible.

ostream& operator<<(ostream& vos, const OurList<class T>& coll)
{
    // OurList wraps an stl list with the same interface as the current library
    // OurListIterator wraps an iterator class used to access OurList

    OurListIterator<T, OurList<class T> > iter((OurList<class T>&)coll);

    // this function gets the first item in the list and then each next one
    while (iter())
    {
        // key returns the value pointed to by the iterator
        vos << iter.key();
    }
};

However, when I compile it I get an error at the vos << iter.key() line:

binary '<<' : no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)

I am guessing that the compiler is complaining because it does not know in advance whether T will be serialisable? However, this works in the current library - am I missing something?

You may try: ( template <typename T> added, class removed).

template <typename T>
ostream& operator<<(ostream& vos, const OurList<T>& coll)
{
    // OurList wraps an stl list with the same interface as the current library
    // OurListIterator wraps an iterator class used to access OurList

    OurListIterator<T, OurList<T> > iter((OurList<T>&)coll);

    // this function gets the first item in the list and then each next one
    while (iter())
    {
        // key returns the value pointed to by the iterator
        vos << iter.key();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM