Skip to content
Permalink
Browse files

Add qgsAsConst(...)

This is the equivalent of std::as_const (which requires c++17) or
qAsConst (which requires Qt 5.7), neither of which we have
as minimum dependancies.

By wrapping implicitly shared Qt containers in qgsAsConst we can
safely use c++ for ranged loops instead of Q_FOREACH. (Since
Q_FOREACH's future is shaky)

See https://www.kdab.com/goodbye-q_foreach/ for further details
on why for causes a detach for Qt containers and why Q_FOREACH
is being removed from Qt.
  • Loading branch information
nyalldawson committed Aug 28, 2017
1 parent 30b46f7 commit 029f741cfaac27b9e1959629afe454faed46e0ca
Showing with 54 additions and 0 deletions.
  1. +2 −0 python/core/qgis.sip
  2. +25 −0 src/core/qgis.h
  3. +27 −0 tests/src/core/testqgis.cpp
@@ -161,6 +161,8 @@ double qgsRound( double number, double places );
:rtype: float
%End



double qgsPermissiveToDouble( QString string, bool &ok );
%Docstring
Converts a string to a double in a permissive way, e.g., allowing for incorrect
@@ -250,6 +250,31 @@ inline double qgsRound( double number, double places )
return static_cast<double>( static_cast<qlonglong>( number * scaleFactor + 0.5 ) ) / scaleFactor;
}


#ifndef SIP_RUN

///@cond PRIVATE

/**
* Adds const to non-const objects.
*
* To be used as a proxy for std::as_const until we target c++17 minimum.
*
* \since QGIS 3.0
* \note not available in Python bindings
*/
// TODO - remove when we target c++17 minimum and can use std::as_const
template <typename T> struct QgsAddConst { typedef const T Type; };

template <typename T>
constexpr typename QgsAddConst<T>::Type &qgsAsConst( T &t ) noexcept { return t; }

template <typename T>
void qgsAsConst( const T && ) = delete;

///@endcond
#endif

/** Converts a string to a double in a permissive way, e.g., allowing for incorrect
* numbers of digits between thousand separators
* \param string string to convert
@@ -41,6 +41,7 @@ class TestQgis : public QObject
void signalBlocker();
void qVariantCompare_data();
void qVariantCompare();
void testQgsAsConst();

private:
QString mReport;
@@ -278,6 +279,32 @@ void TestQgis::qVariantCompare()
QCOMPARE( qgsVariantGreaterThan( lhs, rhs ), greaterThan );
}

class ConstTester
{
public:

void doSomething()
{
mVal = 1;
}

void doSomething() const
{
mVal = 2;
}

mutable int mVal = 0;
};

void TestQgis::testQgsAsConst()
{
ConstTester ct;
ct.doSomething();
QCOMPARE( ct.mVal, 1 );
qgsAsConst( ct ).doSomething();
QCOMPARE( ct.mVal, 2 );
}


QGSTEST_MAIN( TestQgis )
#include "testqgis.moc"

0 comments on commit 029f741

Please sign in to comment.
You can’t perform that action at this time.