-1

I have a templated API function that takes a container of objects:

template <class Container> void fn(Container *container);

It uses some basic methods of std containers and expects to find objects that implement some methods.

I have a set/vector/map of pointers to these objects and I need to call this API.

Does anyone see any way of doing this through standard C++ classes? Short of creating a new class that contains a pointer to the original object and reimplements all of its methods through this pointer?

Some kind of generic wrapper that takes a pointer and implements reference-like behavior?

Related questions (if the answer to those was yes, they would have been possible solutions, but it is not the case):

Inability to overload Dot '.' operator in c++

Why can't I make a vector of references?

mmomtchev
  • 2,497
  • 1
  • 8
  • 23
  • Not sure I understand the problem. Without knowing what `fn` does, and without an example of usage, I don't think you'll get an answer. [Here is a demo of a function taking a vector, a set, and a map](https://godbolt.org/z/a8od1qssh). No need for any wrapper. – Nelfeal Apr 28 '23 at 13:00
  • The function takes a container of objects, I have pointers – mmomtchev Apr 28 '23 at 14:09

1 Answers1

1

Instead of making the values stored in the container implement the member functions, wrap the container to iterate over the actual values instead of pointers.

Say you have std::vector<T*> vec;. You can create a view that iterates over the values after indirecting:

auto reference_view = vec | std::views::transform([](auto* obj) -> auto& { return *obj; });
fn(&reference_view);

(And for a map, it might look like std::views::transform([](const std::pair<auto, auto* const>& pair) -> auto& { return *(pair.second); })).

Artyer
  • 31,034
  • 3
  • 47
  • 75