boostorg / boostorg/json

Add conversion example for a simple struct

Open
#1,125 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
479
Forks
110
Avg merge
10d 3h
Merged PRs (30d)
5

Description

E.g.
```
struct X
{
std::vector a;
int b;
};
```

Be sure to prominently explain that the natural implementation of `value_from`
```
void tag_invoke( boost::json::value_from_tag const&, boost::json::value& jv, X const& x )
{
jv = {
{ "a", boost::json::value_from( x.a ) },
{ "b", boost::json::value_from( x.b ) }
};
}
```
is wrong because the intermediate calls to `value_from` use the default storage, which introduces an unnecessary copy if `jv` uses a different storage.

Instead, what needs to be written is either
```
void tag_invoke( boost::json::value_from_tag const&, boost::json::value& jv, X const& x )
{
jv = {
{ "a", boost::json::value_from( x.a, jv.storage() ) },
{ "b", boost::json::value_from( x.b, jv.storage() ) }
};
}
```
or
```
void tag_invoke( boost::json::value_from_tag const&, boost::json::value& jv, X const& x )
{
jv = {
{ "a", nullptr },
{ "b", nullptr }
};

boost::json::value_from( x.a, jv.at( "a" ) );
boost::json::value_from( x.b, jv.at( "b" ) );
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.