Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

supporting QStringList::join for classes



  • Hello,

    I was wondering if there is any option (override some methods from QString for example) other then derive from it directly that will allow create list of objects and calls join method on them.
    E.g.

    QList<MyClass> l{ob1, ob2, ob3}; 
    QString ls = l.join("\n");
    

    Where MyClass could be represented as a QString.


  • Lifetime Qt Champion

    Hi
    Not really.
    Im not sure what you need it for ?

    You can make a toString() in your class and do
    QList<MyClass> l{ob1.toString(), ob2.toString(), ob3.toString()};

    But if its for debugging there are better options :)



  • a bit buried inside QList but it's doable. What you need to do is define a template class:

    template <> struct QListSpecialMethods<MyClass>{
    protected:
        ~QListSpecialMethods() {}
    public:
    
    };
    

    Now in the public part you can implement the methods you want (join included). For example:

    class MyClass{
    public:
        MyClass(int val = 0)
            :m_value(val)
        {}
        int value() const {return m_value;}
    private:
        int m_value;
    };
    
    template <> struct QListSpecialMethods<MyClass>{
    protected:
        ~QListSpecialMethods() {}
    public:
        int join(int startValue) const{
            const QList<MyClass>* const self = static_cast<const QList<MyClass>*>(this);
            return std::accumulate(self->cbegin(),self->cend(),startValue,[](int a, const MyClass& b)->int{return a+b.value();});
        }
    };
    
    int main(int argc, char **argv)
    {
        QCoreApplication app(argc,argv);
        QList<MyClass> myClassList;
        myClassList.append(MyClass(1));
        myClassList.append(MyClass(2));
        myClassList.append(MyClass(3));
        qDebug() << myClassList.join(4);
        return app.exec();
    }
    

Log in to reply