I hope this is not overly convoluted. I have tried searching through the internet for a while and while I've found a lot of Q/As dealing with templates, inheritance, etc., none of the resources I found dealt with this specific issue:
I'd like to create a wrapper for std::vector<T>
which will only create vectors of type std::vector<MyClass>
or any of its inherited classes.
This would basically look like:
Class Base;
Class Derived : Base;
template <Base T> class myVector{
public:
void add(T);
protected:
std::vector<T> list;
}
The goal is to be able to have a library that will have the following behaviour:
Base A;
Derived D;
int i;
myVector<A> AVector; // This should work
myVector<D> DVector; // This should work
myVector<i> iVector; // This should NOT work
AVector.add(A); // This should work
AVector.add(D); // This should work (through polymorphism)
DVector.add(D); // This should work
DVector.add(A); // This should not work
Can anyone comment on the above question/examples? My ultimate goal is to roll my own basic event handling in c++. In this case, A would be the analogue of c# EventArgs. B would allow for specific EventArgs type. I have no doubt that Boost et al have similar functionality, but I'd like to steer clear of that route for the time being.
In practice the code will work something like (based somewhat on a tutorial that I found somewhere out there on the internet):
template<EventArgs arg> class Event{
typedef void (*fptr)(arg);
std::vector<fptr> listeners;
}
void notifylisteners(arg){
for (typename std::vector<fptr>::iterator iter = listeners.begin(); iter != listeners.end; ++iter)
(**iter)(arg); // there should be a check for a valid reference, in case one of the function pointers becomes invalid
The declaration
Event<myEventHandlerType> myEvent;
would effectively function identically to the C# code:
public event myEventHandlerType myEvent;
Templates are required for this implementation due to the reliance on std::vector. The benefit of using a non-type parameter template here (if it works) is that it would force the use of a specific eventArg parameter type to be passed to all registered handlers, and that errors would fail during compilation.
Any thoughts or comments would be greatly appreciated.
Michael