Acceptable use of typedef?

I have a buffer char(i.e. byte) that I send over the network. At some point in the future I will want to switch the buffer to another type, for example, unsigned charor short. I was thinking of doing something like this:

typedef char bufferElementType;

And whenever I do something with a buffer element, I declare it as bufferElementType, rather than char. Thus, I could switch to another type by changing this typedef (of course, it would not be so simple, but at least it would be easy to determine the places that need to be changed ... there will be bufferElementTypenearby, nearby).

Is this a valid / good use of typedef? Isn't that worth the problem? Will it have a headache at some point in the future? Are programmers going to support programmers to hate me?

I read When should I use Typedef in C ++ , but no one explained it.

+5
source share
3 answers

This is an excellent (and normal) use. You must be careful, however, that, for example, the type you select meets the same signing / unsigned criteria, or that they respond similarly to operators. Then it would be easier to change the type later.

Another option is to use patterns to avoid type fixing until compilation. A class that is defined as:

template <typename CharType>
class Whatever
{
   CharType aChar;
   ...
};

char, , .

+11

typedefs , . , , . typedef - .

: . , . , . typedefs - , , .

+2

, typedef, C.

++ , - ( ), . ( , , , , ..)

, typedef .

Note that when sending data over a network, char and other integer types may not be interchangeable (for example, due to endian-ness). In this case, using a template class with specialized functions may make more sense. (sends <char → sends a byte, sends <short>, converts it to a network byte order first)

Another solution would be to create a BufferElementType class with helper methods (convertToNetworkOrderBytes ()), but I bet it would be redundant for you.

+1
source

All Articles