You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QT6中QList与QVector的from_json模板函数重定义编译错误排查

QT6编译报错"error: redefinition of 'from_json'"的原因及解决

问题场景

使用C++17 MinGW编译以下代码时,QT6环境出现编译错误error: redefinition of 'from_json',但该代码在QT5中可正常编译运行:

#include <QVector>
#include <QList>
#include <QDebug>

template<typename OwnType> void from_json(QVector<OwnType> &p)
{
    qDebug() << "QVector";
}

template<typename OwnType> void from_json(QList<OwnType> &p)
{
    qDebug() << "QList";
}

原因分析

  • QT6对QList的实现做了重大调整:在C++17及以上标准环境下,QList<T>本质是QVector<T>的别名(通过模板typedef实现),两者的类型完全等价。
  • 这导致你定义的两个from_json模板函数,参数类型在编译器看来完全相同,触发了函数重定义错误。
  • 而QT5中QList和QVector是独立的模板类,参数类型不同,编译器会将它们视为两个不同的函数,因此不会报错。

解决办法

  1. 合并实现:由于QT6中QList和QVector等价,无需区分处理,只保留一个函数即可:
template<typename OwnType> void from_json(QVector<OwnType> &p)
{
    qDebug() << "QVector/QList";
}
  1. 版本兼容处理:如果需要同时兼容QT5和QT6,可通过QT版本宏进行条件编译:
#include <QVector>
#include <QList>
#include <QDebug>
#include <QtGlobal>

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
template<typename OwnType> void from_json(QVector<OwnType> &p)
{
    qDebug() << "QVector/QList";
}
#else
template<typename OwnType> void from_json(QVector<OwnType> &p)
{
    qDebug() << "QVector";
}

template<typename OwnType> void from_json(QList<OwnType> &p)
{
    qDebug() << "QList";
}
#endif

内容的提问来源于stack exchange,提问作者RandomPerson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:32:45