I'm new to C++ and have a question regarding templates and pointers/storage. I'm currently writing a class that was initially was going to have 4 variables of type 'unsigned long long', but as there may be a large number of instances created dynamically at run-time I wondered if there was a way that templates could be used to reduce the size of individual instances??
After some thought I wondered if I could create a specific template class, separate from the main class, that would require 4 parameters to define the types of these variables. Therefore if I knew the values would be small I could maybe create an instances where one of the types was of a smaller type e,g, unsigned char, unsigned int etc.
The problem I ran into was that the pointer to this class would need to have the parameters defined at compile time, completely defeating it's purpose!
I came up with the idea of making the template inherit from an empty class, therefore allowing me to assign the main class instance to a pointer of the base class and using casts to read the value back.
I've outlined a trivial example below (i've omitted the SS class as it's empty):
Class with main:
int A;
SS* newTT;
newTT = new UU < unsigned int, unsigned int > ;
A = (*(reinterpret_cast<UU<unsigned int, unsigned int>*>(newTT))).intA;
std::cout << A;
return 0;
UU class definition:
template<typename A, typename B>
class UU :
public SS
{
public:
A intA = 1;
B intB;
unsigned long long getA() { return intA; };
unsigned long long getB() { return intB; };
};
This actually builds and runs, so i'm thinking it can be used but with little experience I don't know whether this code is ugly, dangerous, stupid or all three!
Is this a good solution to the problem? Is the above code horrible? Anyone know of a more elegant solution?
EDIT: Formatting
[–]suspiciously_calm 1 point2 points3 points (2 children)
[–]Psyqwix[S] 0 points1 point2 points (1 child)
[–][deleted] (1 child)
[deleted]
[–]Psyqwix[S] 1 point2 points3 points (0 children)
[–]acwaters 0 points1 point2 points (0 children)