Re: How to remove one structure element
Leon Pollak wrote:
I have the structure
struct tStruct {
int a;
int b;
int c;
....
};
and a lot of working code based on this structure.
Now comes the change, that makes exactly the same processing in all derived
objects, with the only exception: no element 'b' is allowed (the structure
arrives from several communication channels).
The only solution which came to me was:
template <int T> struct tStruct {
int a;
int b[T];
int c;
....
};
which will eliminate 'b' in the case of declaration:
tStruct<0> Object;
No, it won't. Zero-sized arrays are illegal in C++.
But this mans that the existing case
tStruct<1> Object;
requires all code rewriting to change
Object.b = 1;
to the new one:
Object.b[0] = 1;
Obviously, very not desirable rework...
Is there some more elegant way to solve this?
Yes, it's called specialisation.
template<bool> struct tStruct;
template<> struct tStruct<true> {
int a;
int b;
int c;
};
template<> struct tStruct<false> {
int a;
int c;
};
enum { no_b_member = 0, has_b_member };
....
struct tDerivedWithB : tStruct<has_b_member> {...
struct tDerivedOther : tStruct<no_b_member> {...
Of course, if you need them to be convertible to some kind of common
base class, you'll need to have another base class for 'tStruct<*>' and
probably rewrite your streaming code anyway...
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask