Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用c++新标准 #1

Open
mingmoe opened this issue Oct 10, 2020 · 4 comments
Open

使用c++新标准 #1

mingmoe opened this issue Oct 10, 2020 · 4 comments
Labels
enhancement New feature or request

Comments

@mingmoe
Copy link

mingmoe commented Oct 10, 2020

我注意到README个段代码:

取值的同时判断类型
int n;
bool ret = j["boolean"].get_value(&n); // 若取值成功,ret 为 true

c++在新标准中已经对这种情况做出标准做法:使用std::optional.
修改成标准代码:

取值的同时判断类型
int n;
auto ret = j["boolean"].get_value(); // 若取值成功,ret 为 true
//get_value()应该返回std::optional<int>
if(ret.has_value()) n = ret.value();
else { /*do some thing*/}

如果没有什么特殊需求,都应该使用标准库中的方法.

@zekexiao
Copy link

zekexiao commented Oct 23, 2020

auto ret = j["boolean"].get_value();
你这样写如何确认类型?

@mingmoe
Copy link
Author

mingmoe commented Oct 23, 2020

对于已知类型,可以使用

optional<bool> ret_boolean = j["boolean"].get_boolean();
optional<string> ret_string = j["string"].get_string();
optional<double> ret_number = j["number"].get_number();

这样可以获取更高的确定性和可读性

如果你想使用泛型,可以用

std::variant<double,std::string,bool/*other type*/> ret_unknow_type = j["unknow type"].get_vulan();

这同样是来自标准库的方法

@zekexiao
Copy link

貌似 README 里面的 bool ret = j["boolean"].get_value(&n); 方法不可用?编译不过 (我不是作者hhhh)
optional<bool> ret_boolean = j["boolean"].get_boolean(); 这样确实可以
不过个人觉得 variant 没必要,j["unknow type"] 得到的 json_basic 本身就是泛型

@Nomango
Copy link
Owner

Nomango commented Mar 9, 2021

@chhdao 感谢建议,没有使用optional的原因是不想让这个库c++17起步,对用户的要求低一些,暂时保留这个issue吧

@Nomango Nomango added the enhancement New feature or request label May 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants