Is there a way of creating a vector or some other C++ container of template publishers of different types? I would like, if possible, to have a vector of publishers, a vector of subscribers, and a vector of services etc. for each node and then be able to add new ones as needed, even if they use different messages. Is there some sort of template magic or something that would allow me to create such containers to organize my code or do the different types make that impractical?
I can’t tell you if this is the best way, but a way, is to use
That appears to be for ROS1, the issue @peterpolidoro bought up seems unique to ROS2 requiring templated publishers if I’m understanding correctly.
No, unfortunately not. However you can store a vector of their base classes, which is exactly what we do when keeping track of them:
However, this is only useful if you want to only call functions which exist in the base class’s API later, as you cannot safely recast them to their typed derived class. So it depends on what you want to do with them that decides if this is useful or not. For example, if you just want to store them to keep them in scope, this can be useful, but if you want to do something like call
publish on them later, you would need to use something like a
std::variant and the
std::visit functions, which requires C++17.
Right, I read the title/tag a little too fast…