One function for several structs in a void**

Started by
2 comments, last by Madhed 8 years, 3 months ago

Hi,

How can I create different structs with only one function according to one parameter??

I have the next example


#define POSCOL 1
#define POSTEX 2

typedef struct PosCol
{
    XMLFLOAT3 pos;
    XMLFLOAT4 col;
}PosCol;

typedef struct PosTex
{
    XMLFLOAT3 pos;
    XMLFLOAT2 tex;
}PosTex;


void CreateShape(void** ppVerts, int type)
{
   if(type == POSCOL)
   {
      *ppVerts = new PosCol[8];
      (*ppVerts)[0] = //object type PosCol. ERROR! "expression must be a pointer to a complete object type"
      (*ppVerts)[1] = //object type PosCol. ERROR! "expression must be a pointer to a complete object type"
   }
   if(type == POSTEX)
   {
      *ppVerts = new PosTex[8];
      (*ppVerts)[0] = //object type PosTex. ERROR! "expression must be a pointer to a complete object type"
      (*ppVerts)[1] = //object type PosTex. ERROR! "expression must be a pointer to a complete object type"
   }
}

That is the idea.

Someone can help me??

Thanks

Cesar

Advertisement

*ppVerts is of type void*, so you need to cast it to your array's type (PosCol* in this case).

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

Assigning new data to it:


void CreateShape(void** ppVerts, int type) {
    switch (type) {
    case POSCOL: {
        PosCol *pc = new PosCol[8];
        *ppVerts = static_cast<void *>(pc);  // Cast may not be needed here, not sure.
        pc[0].pos = 3; // And other
        return;

    case ...
    }
}

Getting data from it


void CreateShape(void** ppVerts, int type) {
    switch (type) {
    case POSCOL: {
        PosCol *pc = static_cast<PosCol *>(*ppVerts);
        pc[0].pos = 4; // And other
        return;
    ...
...
}
You have tagged your post as c++ but with the typedefs, #defines and void pointers it looks pretty much like c code.

I suggest you look up on c++ templates and function overloading when you are ready.
Both are used to execute different code based on the types you are supplying.

Something like this:


// function overloading: We have two functions named FillVertices
// but they take different typed arrays as parameter, so they can do different things
void FillVertices(PosCol* vertices, size_t length) {
    // set position and color
}

// overload of FillVertices
void FillVertices(PosTex* vertices, size_t length) {
    // set position and texture coords
}

// Templated function: This takes a type argument
// and generates code where "T" is replaced by the actual type you pass in
template<typename T>
T* CreateShape() {
    T* vertices = new T[8];
    FillVertices(vertices, 8);
    return vertices;
}

// Used like this

PosCol* vertices = CreateShape<PosCol>();

This topic is closed to new replies.

Advertisement