-2

With C++ and C we can pass different functions to another function through a pointer to void construct. I would like to do the same, passing structs to a function, like this simple example:

#include <iostream>  
using namespace std;

struct S1 {
    static constexpr int  n=1;
    static constexpr double  v=1.2;
};
struct S2 {
    static constexpr int  n=2;
    static constexpr double  v=3.4;
};

typedef void *Vp;  // this would be (*Vp)() for functions

void func(Vp p) {
    cout << "n=" << p->n << " v=" <<'\n'
    // (fails here with error: 'Vp {aka void*}' is not
    //   a pointer-to-object type)
}
int main() {
    struct S1  s1;
    struct S2  s2;
    cout <<"main: using first data\n";
    func(&s1);
    cout <<"main: using second data\n";
    func(&s2);
    return 0;
}

Does anyone know how to make this work or if it is even possible?
A similar question was asked before, but the answers haven't helped me: passing different structs to a function(using void *)
I know it would be better to use one struct and create different instances, but I already have a header with lots of data loaded into structs this way.

Community
  • 1
  • 1
G.Ramian
  • 19
  • 3

1 Answers1

1

You can't do it without having two separate functions, but you can make the compiler generate them for you. You can use a function template:

template<typename StructType>
void func(StructType *p) {
    cout << "n=" << p->n << " v=" << p->v << endl;
}

Now when you write func(&s1);, the compiler will generate a new function for you, based on the template, called func<S1>, which looks like this:

void func<S1>(S1 *p) { // not real syntax
    cout << "n=" << p->n << " v=" << p->v << endl;
}

and similarly for S2.

user253751
  • 57,427
  • 7
  • 48
  • 90