0

I need a function that receives variadic template arguments and returns a JSON array string.

I was able to reach this point:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template<typename Arg>
void add_value(std::stringstream &result, Arg arg){

  if (result.rdbuf()->in_avail())
    result << ",";

  if (std::is_same_v<Arg, string>) {
    result << "\"" << arg << "\"";
  } else if (std::is_same_v<Arg, const char*>) {
    result << "\"" << arg << "\"";
  } else if (std::is_same_v<Arg, char*>) {
    result << "\"" << arg << "\"";
  } else if (std::is_same_v<Arg, bool>) {
    result << arg;
  } else {
    result << arg;
  }
}

template<typename... Args>
std::string to_json_array(Args... args) {
  std::stringstream result;
  (add_value(result, args), ...);
  return "[" + result.str() + "]";
}

int main() {
  std::string result;
  char aa[10] = "haha";
  char *bb = aa;

  result = to_json_array(123, "Hello", 1.5, string("World!"), true, aa, false, bb, NULL);

  std::cout << result << "\n";
}

But it did not work for booleans and null.

As you can notice, I am not a C++ developer.

If you know another method, you can share it too.

Bernardo Ramos
  • 4,048
  • 30
  • 28

1 Answers1

0

I am sharing the solution I've got with the help of the comments:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template<typename Arg>
void add_value(std::stringstream &result, Arg arg){

  if (result.rdbuf()->in_avail())
    result << ",";

  if constexpr (std::is_same_v<Arg, string>) {
    result << "\"" << arg << "\"";
  } else if constexpr (std::is_same_v<Arg, const char*>) {
    result << "\"" << arg << "\"";
  } else if constexpr (std::is_same_v<Arg, char*>) {
    result << "\"" << arg << "\"";
  } else if constexpr (std::is_same_v<Arg, bool>) {
    result << std::boolalpha;
    result << arg;
    result << std::noboolalpha;
  } else if constexpr (std::is_same_v<Arg, nullptr_t>) {
    result << "null";
  } else {
    result << arg;
  }
}

template<typename... Args>
std::string to_json_array(Args... args) {
  std::stringstream result;
  (add_value(result, args), ...);
  return "[" + result.str() + "]";
}

int main() {
  std::string result;
  char aa[10] = "haha";
  char *bb = aa;

  result = to_json_array(123, "Hello", 1.5, string("World!"), true, aa, false, bb, nullptr, 0);

  std::cout << result << "\n";
}

Thank you all!

Bernardo Ramos
  • 4,048
  • 30
  • 28