Is it possible to have a C++ template function which can access different fields in its input data depending on what type of input data was passed to it?
e.g. I have code of the form:
typedef struct
{
int a;
int b;
}s1;
typedef struct
{
int a;
}s2;
template <class VTI_type> void myfunc(VTI_type VRI_data, bool contains_b)
{
printf("%d", VRI_data.a);
if(contains_b) // or suggest your own test here
printf("%d", VRI_data.b); // this line won't compile if VTI_type is s2, even though s2.b is never accessed
}
void main()
{
s1 data1;
data1.a = 1;
data1.b = 2;
myfunc <s1> (data1, true);
s2 data2;
data2.a = 1;
myfunc <s2> (data2, false);
}
So we want to use field A from many different data types, and that works fine.
However, some data also has a field B that needs to be used - but the code which accesses field B needs to be removed if the template knows it's looking at a data type that doesn't contain a field B.
(in my example, the structures are part of an external API, so can't change)