jeudi 2 août 2018

Save pointer to differents type in a std::vector while iterating

Consider the following function (myfct). When this function returns, data points to either uint16_t, float_t or double_t.

In main(), this function is called in a for loop. I want for each iteration to save "data" in a std::vector with the type it points to. How can I do that? Thanks in advance.

PS: the container must not necessarily be a vector, it can be anything else, I just want to save "data" without loosing the pointer type information.

void myfct(void*&data, int id) {
if(id==1) {
  uint16_t* ptr = ...;  
  data = ptr;
}
else if(id==2) {
  float_t* ptr = ...;  
  data = ptr;
}
else if(id==3) {
  double_t* ptr = ...;  
  data = ptr;
}
}

int main() 
{
    void* dataPtr = nullptr;
    vector<?> myVec; //how should I template my vector? which typename?
    for(int i = 0, i<5, i++) 
    {
        myfct(dataPtr , i);  //note that dataPtr is passed by reference
        myVec.push_back(dataPtr ); //here dataPtr point to either uint16_t, 
        //float_t or double_t. I want to save it with the type it point to.
    }
}

Aucun commentaire:

Enregistrer un commentaire