How to write a function that accept all array-like types in C++?

56 Views Asked by At

I'm writing a json parser as a practice (refering nlohmann), and one senario is that user could initialize json value as an array. Here is part of definition of json class:

class json {
 private:
  /* Alias of json_value data types */
  using json_array = std::vector<json_value>;
  /* using ... */

  union json_value {
    json_array* arr;
    json_object* obj;
    /* json_ ... */
  }

  json_value value_;
}

This class should support these initialiations:

/* assume that json_value could be constructed with */
/* single value in the initializer list below */
json j0{1, 2, "Hello", 3.14, true, false, std::nullptr};
/* initialize with an (multi-dimension) array */
int nums0[] = {1, 2};
json j1 = nums0;
int nums1[][3] = {{1, 2, 3}, {4, 5, 6}};
json j2 = nums1;
/* initialize with sequence containers (vector/array/list/etc...) */
json j3 = std::vector<std::string>{"Hello", "World"};
json j4 = std::vector<vector<float>?{{0.31, -17.5}, {-1.0}};

How could I implement constructor to support sequence containers?

And how to support nested arrays/containers/initializer_lists?

One thing comes into my mind would be is_detected. Using is_detected to check if iterator exists, but I'm wondering if there is a better way to check whether it's a sequnce container.

So far I have no clue about arbitary nested array (N-dimensional).

0

There are 0 best solutions below