【问题标题】:How to get a compiler error when expected type changes预期类型更改时如何获得编译器错误
【发布时间】:2017-05-16 01:53:20
【问题描述】:

我的应用中有一些代码以简化形式显示:

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

我刚刚发现了一个错误,有人将函数 Type() 从:

QString Type() const;

到:

int Type() const;

显然 Qt 对此很好,只是将其转换为导致错误的 JSON。但是当像这样更改类型时,我宁愿得到一个编译器错误。如果将来函数的返回发生变化,我该如何更改它以便我得到编译器错误?

【问题讨论】:

  • 您想特别检查pDevice->Type() 的类型,还是一般的功能更改?
  • 只要它是有效的 C++,编译器就会愉快地编译它。你需要的是Unit Tests

标签: c++ qt c++11


【解决方案1】:

最简单的解决方法是在代码中为返回的Type() 值包含一个static_assert。但是,当然,您不希望到处都这样做。

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

【讨论】:

    【解决方案2】:

    你可以使用独立的函数:

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

    或更通用的:

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

    在这两种情况下,只要Type() 返回 QString 或任何可以转换为 QString 的东西,代码就可以工作。你也可以静态断言 Type() 返回 QString。

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2021-08-03
      • 1970-01-01
      相关资源
      最近更新 更多