I am trying to save and process a list of template class objects with different types of parameters; the template class has two parameterized methods: one returns the type of the parameter and void accepts it as an input.
In particular, I have a template class that is defined as follows:
template<typename T> class Test { public: virtual T a() = 0; virtual void b(T t) = 0; };
And various specifications, such as:
class TestInt : public Test<int> { public: int a() { return 1; } void b(int t) { std::cout << t << std::endl; } }; class TestString : public Test<std::string> { public: std::string a() { return "test"; } void b(std::string t) { std::cout << t << std::endl; } };
I would like to be able to store different objects in the same list like TestInt and TestString and scroll through it calling one method as input to another, for example:
for (auto it = list.begin(); it != list.end(); ++it) (*it)->b((*it)->a());
I looked at boost::any , but I can not pass the iterator to a specific class, because I do not know the specific parameter type for each saved object. It might not be possible to do this in a statically typed language like C ++, but I was wondering if there could be a way around it.
Just for completeness, I’ll add that my common goal is to develop a “parameterized observer”, namely the ability to define an observer (like the Observer template) with different parameters: the Test class is an observer class, and a list of different types of observers that I'm trying to correctly determine is stored in the class of the subject, which notifies them of all methods a() and b() .
source share