我认为有几种方法可以解决您的问题:
选项1(如我的评论中所述)
可以像这样使用动态转换:
bool makeJsonData(void* obj) {
QJsonObject* asObj = dynamic_cast<QJsonObject*>(obj);
QJsonArray* asArray = dynamic_cast<QJsonArray*>(obj);
if (asObj) {
//do what you would if it were an object
}
else if (asArray) {
//do what you would if it were an array
}
else {
//cast fail. Returning false to tell the caller that they passed bad data
//an alternate (probably better) would be to throw an exception
return false;
}
}
选项 2
老实说,我觉得这项业务void*
是错误的做法。做事void*
几乎总是一种代码味道(它消除了编译时检查,使我们免于自己踩到自己的脚),在这种情况下,我认为你这样做的方式需要工作。此外,dynamic_cast
需要可能并不总是打开的RTTI (编译器支持、性能问题等)。
我查看了我机器上的 Qt 头文件,据我所知,QJsonObject
并QJsonArray
没有真正继承任何东西,所以沿着将其更改void*
为基本类型的路线,以保持类型检查的外观不太行。
我会做的是:
- 制作两种不同的方法。一种用于处理数组,一种用于处理对象。他们有不同的方法和不同的事情你可以做,所以这对我来说很有意义。您甚至可以保持相同的名称,以便它们重载。
- 有另一种方法,里面有你常用的东西。我假设您的函数正在尝试将一些数据添加到传递的数组或对象中。创建一个创建数据的方法(即
QJsonObject createJsonData()
)并在上面提到的两个方法中调用它。
这个想法是在保持类型检查的同时减少代码重复。您花在处理这两种情况的一个额外方法上所花费的时间可能远远少于在意外将某些内容传递给void*
您从未打算传递的指针后调试代码所花费的时间。
选项 3
或者,您可以使用QJsonValue
,将函数的返回类型更改为QJsonValue
,并使其返回新对象而不修改原始对象。此外,QJsonValue
该类具有您可以用来做前面提到的事情的有趣isArray
/方法。isObject
一个例子:
QJsonValue makeJsonData(const QJsonValue& val) {
if (val.isObject()) {
QJsonObject obj = val.toObject();
//do your stuff, modifying obj as you please (perhaps calling another method so that this can have less repetition
return QJsonValue(obj);
}
else if (val.isArray()) {
QJsonArray arr = val.toArray();
//do your stuff, modifying arr as you please (perhaps calling another method so that this can have less repetition
return QJsonValue(arr);
}
else {
throw "Invalid Value Type";
}
}
老实说,我更喜欢这种模式,但我知道采用您提到的方式是有原因的,例如避免无偿分配内存。