xzaton jw
xzaton jw

Reputation: 71

C++ Paramater pack expansion over chained function calls

It is common for libraries to have types which return instances of themselves from member functions to encourage chaining calls. For example, nlohmann json:

auto my_data = my_json_object["first key"]["second key"];

Is there some way to call a member function using the contents of a parameter pack? e.g.:

template<class... Keys>
auto get_elem(json json, Keys... keys)
{
   return json([keys]...); // -> json[keys[0]][keys[1]]...[keys[N]]
}

auto my_data = get_elem(my_json_object, "first key", "second key");

Upvotes: 4

Views: 151

Answers (2)

user1095108
user1095108

Reputation: 14603

KamilCuk's answer is the best, this one is just food for thought:

auto& get(auto& j, auto&& a, auto&& ...b)
{
  auto e(&j[a]);

  return ((e = &e->operator[](b)), ...), *e;
}

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 141493

The simplest there is:

template<typename A, class First>
auto get_elem(A json, First first) {
   return json[first];
}


template<typename A, class First, class... Keys>
auto get_elem(A json, First first, Keys... keys) {
   return get_elem(json[first], keys...);
}

Upvotes: 3

Related Questions