I am doing a challenge for myself and writing a program in C++ without using classes and class related machinery. Additional conditions are I can use everything from stl and have full type safety, meaning no raw pointers or casting from one type to another. I am now in a situation where I'm not sure how to proceed with the constraints I have put on myself.
Problem: I want to create a std::vector of functions, but each of those functions might take a different data type, and operate on that type only. Example:
struct DataAndFunction {
AnyDataType data;
std::function<void(AnyDataType&)> functionOperatingWithData;
};
...
std::vector<DataAndFunction> listOfFunctions;
...
for(auto& dataAndFunc : listOfFunctions) {
dataAndFunc.functionOperatingWithData(dataAndFunc.data);
}
then there either would be different kind of AnyDataType
and accompanying functions.
I know it could be solved in a couple of ways:
with classes using polymorphism, where
std::vector< DataAndFunction > listOfFunctions;
would just take a base class as a template parameter, and would have virtual method, that would be implemented by child classes, each with their own private data members, but the point of my challenge is to not use this pattern.
- I could pass
void*
as data and function signature, and inside each function I would cast the data to the appropriate type, but I want to use type safety and only smart pointers
I could also make DataAndFunction
struct a generic by adding template parameter, but then how do I make a vector that could be filled with not just with of DataAndFunction<int>
for example, but any template parameter?
And how would this problem be solved in a more functional style? How would a functional solution look in C++ that would operate on a list of functions each taking a different type of argument? Without using inheritance of course.
Or am I just asking how to emulate a virtual table?