I don't know if it's possible to achieve what I'm trying but maybe someone can guide me in the right direction. Sidenote: this is on an embedded system.
I have an SPI communication that returns a std::vector<int>
representing a set of registers. This is done in a separate thread so asynch.
To handle this, I create an object on every read
call containing a std::promise<std::vector<int>>
(and some other information) and directly return the future
of it, so the caller can wait for the result.
Once the SPI transfer is complete, I set the value of the promise accordingly. So far so good.
Now what I'd like to do is to not always return a future of type std::vector<int>
but do some preprocessing on the vector and return either int
or double
or even a struct
.
I thought I can achieve that by handing an anonymous function to the read
function and store a reference in the object. This function would then be called before the promise is assigned.
The problem I now have is that the return type of this function directly affects the return type of my promise and the object storing them is not always the same anymore. So I thought I just template it
template <class ret_type>
class obj{
public:
std::promise<ret_type> prms;
ret_type (*map_function)(std::vector<int>);
...
};
But now I have to problem that my vector containing these objects (the SPI queue) that was of type std::vector<obj>
cannot hold objects of different types.
Is there a proper way to solve that?
edit: I'd use the vector in a way like
for(auto &element : vector){
std::vector<int> answer_from_spi = spi_read();
element.prms.set_value(element.map_function(answer_from_spi));
}