Is there a way to change what data members are contained in a templated struct based on the parameters? For instance:
template<int Asize> struct intxA
{
#if (Asize <= 8)
int8 num = 0;
#elif (Asize <= 16)
int16 x = 1;
#endif
};
In implementation:
intxA<3> struct8;
intxA<11> struct16;
I have tried the code above, however, the data member "num" is always present, no matter the value of Asize. Is there a way to do this in C without doing it manually?
CodePudding user response:
With std::conditional
:
template<int Asize> struct intxA
{
std::conditional_t<(Asize <= 8), int8, int16> m = Asize <= 8 ? 0 : 1;
};
But if you want to give different name, you have to do specialization
CodePudding user response:
Yes, you can do it with partial specialization.
template<int Asize, typename = void> struct intxA
{
};
template <int Asize>
struct intxA<Asize, std::enable_if_t<Asize <= 8>>
{
int8 num = 0;
};
template <int Asize>
struct intxA<Asize, std::enable_if_t<(Asize > 8 && Asize <= 16)>>
{
int16 x = 1;
};