Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a qreal literal

Tags:

literals

qt

In the Qt docs it says that a qreal is a

Typedef for double unless Qt is configured with the -qreal float option.

This basically means almost always double but float on ARM devices.

I want to use qreal literals however I don't know how to write them.

qreal someValue = calcFunc();
qreal min = qMin(someValue, 0.0);

Where 0.0 is a double literal and 0.0f would be a float literal. On ARM this is a compile arror as there is no qMin(float, double) function.

I could write static_cast<qreal>(0.0) but this seems overly verbose.

So how do I define a qreal literal?

like image 437
Troyseph Avatar asked Jun 17 '16 08:06

Troyseph


1 Answers

You can use C++11 user defined literals:

#include <QtCore>

constexpr qreal operator "" _qr(long double a){ return qreal(a); }

int main() {
   qreal a = 3.0_qr;
   Q_ASSERT(qMin(a, 4.0_qr) == a);
}

If they're not available on your platform, you can explicitly construct qreals when you need them:

using _qr  = qreal;

int main() {
   qreal a = _qr(3.0);
   Q_ASSERT(qMin(a, _qr(4.0)) == a);
}
like image 57
Kuba hasn't forgotten Monica Avatar answered Oct 01 '22 19:10

Kuba hasn't forgotten Monica