简体   繁体   English

我如何序列化模板类

[英]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. 它涉及到用STL和boost替换过时的库,同时保持接口尽可能类似于人类。

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: 但是,当我编译它时,在vos << iter.key()行出现错误:

binary '<<' : no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion) 二进制'<<':未找到采用类型为'T'的右侧操作数的运算符(或没有可接受的转换)

I am guessing that the compiler is complaining because it does not know in advance whether T will be serialisable? 我猜编译器在抱怨,因为它不预先知道T是否可序列化? However, this works in the current library - am I missing something? 但是,这在当前库中有效-我缺少什么吗?

You may try: ( template <typename T> added, class removed). 您可以尝试:(添加template <typename T> ,删除class )。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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