Skip to content

Default value of std::optional #163

@AnsiV01

Description

@AnsiV01

Hi

Having sample data to connect to the database, which have default values, I wanted to be able to override, some of them. For example:

struct in c++:

struct DatabaseAccessData
{
	std::optional<std::string> login{ "admin" };
	std::optional<std::string> password{ "admin" };

	std::optional<std::string> ip{ "127.0.0.1" };
	std::optional<std::string> database{ "test" };
	std::optional<unsigned short> port{ 3306 };
};

Json file:

{
	"ip": "192.168.4.1",
	"database": "beta",
	"port": 33061
}

And now I read the data from the JSON file:

DatabaseAccessData database{};
rfl::Result<DatabaseAccessData> res = rfl::json::load<DatabaseAccessData>("database.json");

if (res.error())
{
	std::cout << "Parsing Error: " << res.error()->what() << std::endl;
	return false;
}

database = *res; //<--  it's all his fault

std::cout
	<< "Login: " << (database.login ? *database.login : std::string{ "[Empty]" }) << "\n"
	<< "Password: " << (database.password ? *database.password : std::string{ "[Empty]" }) << "\n"
	<< "IP: " << (database.ip ? *database.ip : std::string{ "[Empty]" }) << "\n"
	<< "Database: " << (database.database ? *database.database : std::string{ "[Empty]" }) << "\n"
	<< "Port: " << *database.port << "\n";

and after displaying it, I find that I have lost the login and password values:

Login: [Empty]
Password: [Empty]
IP: 192.168.4.1
Database: beta
Port: 33061

Is there any other way to achieve my goal?

I also thought about using rfl::to_view, but the problem would be when there are other structures that contain other structures in the structure.

I think it would be nice to be able to do something like this

DatabaseAccessData database{};
std::optional<rfl::Error> err = rfl::json::load<DatabaseAccessData>("database.json", database);

if (err)
{
	std::cout << "Parsing Error: " << err->what() << std::endl;
	return false;
}

where as an argument of the load function we can add our instance of the structure.

Have a nice day

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions