PDA

View Full Version : Cast QList<Foo*> to QList<const Foo*>



vfernandez
4th October 2010, 17:04
Is it possible to cast a QList<Foo*> to QList<const Foo*> without creating a new list and copying all the values?

For example:

#include <QtCore>

class Foo
{
public:
Foo(int bar, const QString& tar)
: m_bar(bar),
m_tar(tar)
{
};

int m_bar;
QString m_tar;
};

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

QList<Foo*> list;
list << new Foo(23, "blah");
list << new Foo(61, "whoo");
list << new Foo(79, "oops");

QList<const Foo*> constList(list);

qDeleteAll(list);
}

This gives a compilation error, which is normal since QList<const Foo*> doesn't have a constructor for Foo*:


main.cpp: In function ‘int main(int, char**)’:
main.cpp:25:40: error: no matching function for call to ‘QList<const Foo*>::QList(QList<Foo*>&)’
/usr/include/QtCore/qlist.h:118:12: note: candidates are: QList<T>::QList(const QList<T>&) [with T = const Foo*]
/usr/include/QtCore/qlist.h:117:12: note: QList<T>::QList() [with T = const Foo*]
make: *** [main.o] Error 1