Вы также можете использовать анонимную функцию, если вам нужна поддержка es3:
function openSubNavs2()
{
var allToggleBs = document.querySelector('ul#nav').getElementsByTagName('b');
for (var i=0; i<allToggleBs.length; i++)
{
(function(toggleB) {
toggleB.addEventListener('click', function() {
toggleB.className = 'show';
});
})(allToggleBs[i]);
}
}
What bridges do you need?
You can use all the Qt container classes with std algorithms. Most of the time I prefer the Qt container classes because I'm sure they use the copy-on-write idiom (constant time operation). Qt's foreach function creates a copy of the container so its nice that you know for sure it is a constant time operation.
If the Qt signal slot mechanism is to slow you can switch to the boost alternative. Самое замечательное в Qt signal / slot - это соединение сигнал / слот между двумя потоками.
QtConcurrent отлично работает с BOOST.Lambda
Для «общих» дочерних и родительских отношений я использую эту вспомогательную функцию.
template <class Object>
static boost::shared_ptr<Object> makeSharedObject()
{
using namespace boost;
using namespace boost::lambda;
return boost::shared_ptr<Object>(
new Object(),
bind( &Object::deleteLater, _1 ) );
}
Контейнеры Qt не поддерживаются Boost.serialize, вам придется писать функции сериализации самостоятельно. I would love a bridge between the Qt streaming classes and Boost.archive.
Here is my QList serialization template you can figure out the rest of them ...
///\file document is based on "boost/serialization/list.hpp"
namespace boost {
namespace serialization {
//---------------------------------------------------------------------------
/// Saves a QList object to a collection
template<class Archive, class U >
inline void save(Archive &ar, const QList< U > &t, const uint /* file_version */ )
{
boost::serialization::stl::save_collection< Archive, QList<U> >(ar, t);
}
//---------------------------------------------------------------------------
/// Loads a QList object from a collection
template<class Archive, class U>
inline void load(Archive &ar, QList<U > &t, const uint /* file_version */ )
{
boost::serialization::stl::load_collection<
Archive,
QList<U>,
boost::serialization::stl::archive_input_seq<Archive, QList<U> >,
boost::serialization::stl::no_reserve_imp< QList<U> > >(ar, t);
}
//---------------------------------------------------------------------------
/// split non-intrusive serialization function member into separate
/// non intrusive save/load member functions
template<class Archive, class U >
inline void serialize(Archive &ar, QList<U> &t, const uint file_version )
{
boost::serialization::split_free( ar, t, file_version);
}
} // namespace serialization
} // namespace boost
BOOST_SERIALIZATION_COLLECTION_TRAITS(QList)
If you want Boost.Bind to handle QPointer as a normal pointer (like shared_ptr):
namespace boost {
template<typename T> T * get_pointer(QPointer<T> const& qPointer)
{
return qPointer;
}
}
Using QIODevice
where a std::stream
is needed
namespace boost {
namespace iostreams {
class IoDeviceSource
{
public:
typedef char char_type;
typedef source_tag category;
explicit IoDeviceSource(QIODevice& source)
: m_source(source)
{
}
std::streamsize read(char* buffer, std::streamsize n)
{
return return m_source.read(buffer, n);
}
private:
QIODevice& m_source;
};
class IoDeviceSink {
public:
typedef char char_type;
typedef sink_tag category;
explicit IoDeviceSink(QIODevice& sink)
: m_sink(sink)
{
}
std::streamsize write(const char_type* buffer, std::streamsize n)
{
return m_sink.write(buffer, n);
}
private:
QIODevice &m_sink;
};
class IoDeviceDevice {
public:
typedef char char_type;
typedef seekable_device_tag category;
explicit IoDeviceDevice(QIODevice& device)
:m_device(device) {
}
std::streamsize write(const char_type *buffer, std::streamsize n)
{
return m_device.write(buffer, n);
}
std::streamsize read(char* buffer, std::streamsize n)
{
return m_device.read(buffer, n);
}
stream_offset seek(stream_offset off, std::ios_base::seekdir way)
{
using namespace std;
stream_offset next(0);
if(way==ios_base::beg)
{
next = m_device.pos();
}
else if(way==ios_base::cur)
{
next = m_device.pos() + offset;
}
else if(way==ios_base::end)
{
next = m_device.size() -1 + offset;
}
else
{
throw ios_base::failure("bad seek direction");
}
if( !m_device.seek(next) )
{
throw ios_base::failure("bad seek offset");
}
return m_device.pos();
}
private:
QIODevice &m_device;
};
}
}
Example
#include <iostream>
#include <QFile>
#include <boost/iostreams/stream.hpp>
#include "iodevicestream.h"
int main(int argc, char *argv[])
{
namespace io = boost::iostreams;
QVector<int> data;
QFile fl("temp.bin");
fl.open(QIODevice::ReadWrite);
io::stream<io::IoDeviceDevice> inoutput( fl );
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(inoutput, "\n"));
inoutput.flush();
inoutput.seekg(0, std::ios_base::beg);
std::cout << inoutput;
return 0;
}
В общем, вы добьетесь большего успеха при использовании QT, если будете придерживаться классов Коллекции QT, а не использовать STL. В Qt, STL или Boost нет ничего как такового, что препятствовало бы их использованию друг в друге.
Вы должны быть осторожны при использовании интеллектуальных указателей. QT имеет отношения родитель / потомок, которые могут позаботиться об уничтожении объектов, освобождении объектов. когда они находятся под контролем Qt, вы рухнете.
В чем именно проблема?
Вы можете игнорировать все классы коллекций Qt, если хотите, и использовать эквиваленты STL.
Точно так же вы можете использовать кроссплатформенные файловые / сетевые библиотеки Boost.
Основная причина использования собственных Qt, вероятно, заключается в том, что boost не обязательно так широко доступен, особенно на мобильных устройствах. Некоторые библиотеки Boost немного сложнее в использовании, чем библиотеки Qt для простых задач.