parsley72
parsley72

Reputation: 9087

How to get a compiler error when expected type changes

I have some code in my app which in simplified form goes:

QVariantMap deviceMap;
deviceMap.insert("Model", pDevice->Type());
QJsonDocument jsonDoc = QJsonDocument::fromVariant(deviceMap);
QString str = jsonDoc.toJson(QJsonDocument::Compact);

I've just found a bug where someone changed the function Type() from:

QString Type() const;

to:

int Type() const;

Obviously Qt was fine with this and just converted it to JSON which caused the bug. But I'd rather get a compiler error when a type is changed like this. How can I change this so I get a compiler error if the return of a function changes in future?

Upvotes: 0

Views: 70

Answers (2)

Pavel P
Pavel P

Reputation: 16892

You could use free-standing functions:

void insertModel(QVariantMap& deviceMap, const QString& str)
{
    deviceMap.insert("Model", str);
}
insertModel(deviceMap, pDevice->Type());

or more generic:

void insertString(QVariantMap& deviceMap, const char* key, const QString& str)
{
    deviceMap.insert(key, str);
}
insertString(deviceMap, "Model", pDevice->Type());

In both cases code will work as long as Type() returns QString or anything that can be converted to a QString. You may also static_assert that Type() returns QString.

Upvotes: 1

Henri Menke
Henri Menke

Reputation: 10939

The simplest workaround would be to include a static_assert for the returned value of Type() in the code. But of course, you do not want to do that everywhere.

static_assert( std::is_same<decltype(pDevice->Type()), QString>::value,
               "Type mismatch, expected QString" );
deviceMap.insert("Model", pDevice->Type());

Upvotes: 2

Related Questions