Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 505
xzaton jw Avatar asked Oct 29 '25 08:10

xzaton jw


1 Answers

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...);
}
like image 199
KamilCuk Avatar answered Oct 30 '25 22:10

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!