Question

I have a base class that has an enum value that I am using in the derived class. The base class is a Table<> and the derived class is a Matrix<>. Now the enum value in Table<> is TABLE_SIZE which is used in the Matrix<> class. Since TABLE_SIZE does not make a lot of sense (it does a little!) in the matrix class, I thought I would typedef it to something more consistent with Matrix<> (MATRIX_SIZE).

typedef TABLE_SIZE MATRIX_SIZE;

That didn't work, which was a bit surprising. I am guessing I can't typedef the value because the enumeration is a type but not the values (not sure if that is a correct observation)?. So, now the question is, how-do-I/can-I accomplish the above?

EDIT: One thing I forgot to mention is that I do not want the Matrix class to increase in size (yes I realize it is a tiny increase and wouldn't matter for most people, in my case, it does).

Was it helpful?

Solution

You can define an enumeration: enum { MATRIX_SIZE = TABLE_SIZE };

OTHER TIPS

typedef is for types, not values. Use

static const size_t MATRIX_SIZE = TABLE_SIZE;

(Assuming size_t is the correct type here.)

Even better, just rename TABLE_SIZE to SIZE or size; since it's a member, it can hardly be confused with any of the other sizes in your program.

I'm going to take a different tack here.

Since TABLE_SIZE does not make a lot of sense (it does a little!) in the matrix class,

Rhetorical question: If it doesn't make sense, why are you doing it? The answer is that there is some reason you need your Matrix to be the same size as the base Table. So why hide the fact? Be explicit. Don't obscure the fact the matrix size and table size are one and the same. Think about the poor future maintainer (probably you), who has to go plow through that extra level of indirection (probably with no comment as to why).

Not only should you be explicit, that you are intentionally making the matrix size the same as the underlying table size is a design decision that is worthy of a comment.

Always program as if the future maintainer is a homicidal maniac who knows where you live.

typedef is the keyword for declaring a type alias, but TABLE_SIZE is not a type.

You could use the preprocessor:

#define MATRIX_SIZE TABLE_SIZE

(Waiting for the unsubstantiated "macros are evil!" claims. Go on, I dare you.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top