Common function which accepts different structures as parameter

New to c++ and i am trying to write a common function which accepts a structure with common fields. For example

struct A
{
int id,
int p_id,
json_t* ptr
}

struct B
{
int id,
int p_id,
long lg,
cha* tptr
}

struct C
{
int id,
int p_id,
int test
}

I want to use a common function which accepts any of these struct as parameter.
Can i have a common structure with id, p_id and a void* which accepts anything and in the receiving end again convert void* to required structure. Is this a correct in c++ ? or i shoud just make use of polymorphism?

You can do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
enum class StructType{
    A,
    B,
    C,
};

template <typename T>
StructType get_type(const T &);

//Type-specific processing.
void foo_helper(A &);
void foo_helper(B &);
void foo_helper(C &);

template <typename T>
void foo(T &x){
    //Some processing common to all types.
    switch (get_type(x)){
        case StructType::A:
            foo_helper(x);
            break;
        case StructType::B:
            foo_helper(x);
            break;
        case StructType::C:
            foo_helper(x);
            break;
    }
}

However, I would recommend redesigning the structs instead. Either use a union inside a single struct, or use a polymorphic class.
With function overloading:
1
2
3
void f(const A& s);
void f(const B& s);
void f(const C& s);

With inheritance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Base
{
int id;
int p_id;
};

struct A : public Base
{
  json_t* ptr;
}

struct B: public Base
{
long lg,
cha* tptr;
};

struct C : public Base
{
  int test;
};


BTW
don't use void* in C++, there is a better way -> std::any
https://en.cppreference.com/w/cpp/utility/any
don't use char*, better to use std::string
http://www.cplusplus.com/reference/string/string/
Topic archived. No new replies allowed.