[Interest] constexpr construct a QLatin1String from a raw string literal

Gunnar Roth gunnar.roth at gmx.de
Tue Mar 14 17:03:11 CET 2017


Hello Qt and C++ experts.
 
I try to let the compiler generate a QLatin1String instance from a string literal.
Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s) Q_DECL_NOTHROW : m_size(s ? int(strlen(s)) : 0), m_data(s) {}

cannot really do this as it uses strlen,  is this right? Only a QLatin1String(nullptr) would be generated at compile time.
 
There is also 
Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s, int sz) Q_DECL_NOTHROW : m_size(sz), m_data(s) {}

but this has an additonal length parameter. 
So I wrote this:
class Latin1Literal : public QLatin1String
{
  public:
    template <std::size_t N>
    Q_DECL_CONSTEXPR inline explicit Latin1Literal(const char (&s)[N]) Q_DECL_NOTHROW : QLatin1String(s, N - 1)
    {
    }
};
 
I can then do something like    if (arguments.contains(HmiGfx::RHQt::UtQt::Latin1Literal("--fullscreen")))
or define a variable like Q_CONSTEXPR Latin1Literal MY_PREFIX("Prefix");

My question is now, is this the right thing to do and could something like that be added to Qt itself?

Regards,
Gunnar Roth





More information about the Interest mailing list