C++ 如果我没有';不需要注意内部功能状态?
这个问题有点让人困惑,所以让我解释一下我的困境 我正在使用C++ 如果我没有';不需要注意内部功能状态?,c++,json,qt,templates,design-patterns,C++,Json,Qt,Templates,Design Patterns,这个问题有点让人困惑,所以让我解释一下我的困境 我正在使用nlohman::json并尝试在qt5.8中的nlohman::json值类型和QStrings之间进行转换。为了进行这些转换,我得出的结论是,对于json值类型,我需要使用json库json::is_typexxx。结果是这样的: QString convertQString(const json &json_in) { if (json_in.is_number_integer()) { return
nlohman::json
并尝试在qt5.8中的nlohman::json
值类型和QString
s之间进行转换。为了进行这些转换,我得出的结论是,对于json值类型,我需要使用json库json::is_typexxx
。结果是这样的:
QString convertQString(const json &json_in) {
if (json_in.is_number_integer()) {
return //QString integer conversion
} else if (json_in.is_number_float()) {
return //QString float conversion
} else if (json_in.is_string()) {
return //QString std::string conversion
} else if (json_in.is_boolean()) {
return //QString bool conversion
}
return // QString no type found default
}
我很快意识到我需要将qstring转换回nlohman::json
的值,为此我开始编写以下函数
void convertJson(.../**notimportant**/... json& json_out){
... /**more stuff here**/
if (json_out.is_number_integer()) {
...
} else if (json_out.is_number_float()) {
...
} else if (json_out.is_string()) {
...
} else if (json_out.is_boolean()) {
...
}
...
}
很快就意识到我只是在写同样的逻辑来检查类型。当然,我认为这是使用模板方法模式的绝佳机会,并开始编写以下类:
template<typename T>
class JsonChoice {
protected:
T makechoice(const nlohmann::json &json_in);
virtual T ifinteger() = 0;
...// other functions that follow the "iftypexxx()" convention
};
template<typename T>
T JsonChoice::choice(const nlohmann::json &json_in) {
if (json_in.is_number_integer()) {
return ifinteger();
... //you get the pattern...
}
QStringConverter : public JsonChoice<QString>{
...
protected:
QString ifinteger();
... //etc
};
// friend define operator ()?
JsonConverter : public JsonChoice<nlohmann::json>{
...
protected:
nlohmann::json ifinteger();
... //etc
};
// friend define operator ()?
因此,我对不遵循约定持谨慎态度,但由于我不需要任何状态,每次我想使用本质上是一个内部逻辑根据签名而切换的函数时,强迫自己创建一个变量似乎不是一个好主意。我开始怀疑我是否应该使用函子来完成这项任务,因为我可以在技术上对流程的每个部分进行模板化,以简单地创建一个函数。要创建一个包含所有静态成员的函子类,将其用作函子,这是解决此问题的适当方法吗
但是,静态重载()是一个问题,我不确定是否应该像这样将另一个类函数包装到另一个函数中来解决此问题:
QString convertQstring(const nlohmann::json &json_in){
return QStringConverter.makechoice(json_in);
}
或者只是对函数的每个部分进行模板化(我觉得这听起来既烦人又难看),以概括选择开关,即:
template<typename returnval, typename integerfunctemplate, ...>
returnval convert( const nlohmann::json &json_in){
if (json_in.is_number_integer()) {
return integerfunctemplate();
...
}
模板
returnval转换(常量nlohmann::json和json_in){
if(json_in.is_number_integer()){
返回integerfunctemplate();
...
}
出于好奇,你有什么理由不能使用QVariant吗?@BruceFeldman我不确定QVariant是如何工作的,但看看这些文档,我看不出它会有什么帮助。我想,与QJsonValue结合使用,它可以为你处理整个类型检查系统,你可以将输出作为一个漂亮的字符串
template<typename returnval, typename integerfunctemplate, ...>
returnval convert( const nlohmann::json &json_in){
if (json_in.is_number_integer()) {
return integerfunctemplate();
...
}