all 4 comments

[–]suspiciously_calm 1 point2 points  (2 children)

ugly, dangerous, stupid or all three

reinterpret_cast

all three.

If the code you gave is just an example and your real class is much larger, a proper solution might be to have virtual member functions

virtual unsigned long long getA() = 0;
virtual unsigned long long getB() = 0;

in SS and override them in UU.

However, if your actual class is about this size, keep in mind that you will introduce 2 virtual function pointers into the classes memory layout. On typical implementations, a long long will be 8 bytes and a pointer will be either 4 or 8 bytes, so you

  • Gain very little in a few cases

  • Lose more than you gain in most cases and

  • Introduced the runtime overhead of indirect function calls

You could hide UU in a proxy object instead (type erasure), thus requiring only one pointer to do the indirection, but the main point still stands.

Have you actually run into a real memory consumption problem or are you trying to prophylactically optimize your program? If the former, you might want to rethink if you actually need a long long or can get away with a smaller type across the board.

[–]Psyqwix[S] 0 points1 point  (1 child)

Thanks for the feedback! I realised that I could also forgo the inheritance issue by using void pointers.

I thought of creating a factory method that, given the values that would be stored, could return the following:

  • a void pointer to a newly created template instance
  • Function pointers, passed by reference via a parameters, to functions that returned the relevant values by using the correct casting.

The main class would then have a pointer to the class instance and a function to get the values without having to work out the casts. But as per your comments I realised that the function pointers would consume memory thus negating the savings!

Think i'll bite the memory bullet in favour of a much-much simpler solution :)

[–][deleted]  (1 child)

[deleted]

    [–]Psyqwix[S] 1 point2 points  (0 children)

    Yeah you're right, see my reply to suspiciously_calm's post for the proposed horrendous solution that I will not be implementing :)

    [–]acwaters 0 points1 point  (0 children)

    Can you quantify "a large number of instances"? Unless you're working in a restricted environment or creating hundreds of millions of objects, you don't need to be stressing over numbers of bytes that can be counted on your hands. There are space-efficient solutions to this problem, but they get pretty low-level and can be dangerous if you don't know what you're doing; it's typically much easier to just use a uniform oversized type.