Search code examples
c++variadic-functions

Creating a function that takes a container "X" as a parameter, which passes X.size() parameters to a variadic function that it calls


I am currently working on an HTTP API that I want to use to perform CRUD operations on a database. I try to write the code for it as generic and modular as possible. I am using the MySQL X DevAPI.

Currently, I am stuck on the following problem:

mysqlx::Result MySQLDatabaseHandler::jsonToCUDOperation (const nlohmann::json& json, mysqlx::Table& table, int crudEnum)

The function above takes as an argument a reference to a json object, a reference to a table object and an integer.

What I want this function to do is:

  • Check the integer to decide what operation to perform
  • Check the size of the json to know how many parameters are gonna be passed to the variadic function of the X DevAPI that is used to perform the operation.
  • Assemble and perform the function call

For example, assume a table "users", as well as a json object "X" with following contents:

{"id":1,"username":"test_user","email":"test@test.com","first_name":"test"}

Now, when I would call the function like this

jsonToCUDOperation(X, users, MySQLDatabaseHandler::cud::create);

I would want the function to parse the json object and call the mysqlx::Table::Insert function with parameters (and parameter count) based on the json object's keys and values, so eventually calling

users.insert("id", "username", "email", "first_name") .values("1", "test_user", "test@test.com", "test").execute();

I first thought about achieving this behavior using a template function, but then I figured it wouldn't make sense, since the template function definitions are generated at compile time, and what I desire would require dynamic behavior at runtime. So I thought that it is not possible to design this as I intend, as it was my understanding that the behavior of a C++ function cannot change at runtime based on the parameters you pass to it. But I've figured that before I begin developing a solution which can only handle a limited json object size, I'd ask here to assure that I actually cant do what I want.

Thanks in advance for enlightening me


Solution

  • You can actually just pass STL containers to the CRUD functions provided by MySQL's X DevAPI