I have a template class, and would like to write a member method that’s able to recognize what kind of type the template has been instantiated to.
I need to create a string identifier containing the following information on the type:
- bit depth
- signed or unsigned
- floating point or int or char
The method should return a string composed in the following way:
string: (BIT_DEPTH)-(U|S)-(C|I|F)
BIT_DEPTH -> is the number of bits used to represent type
U | S -> describes if type is signed or unsigned
C | I | F -> describes if type is char int or floating point
I thought of a way to find to bit depth:
int bitDepth = sizeof(TemplateType) * 8;
is it ok?
But have no idea on how to find the other information I need, unless a switch-case statement like the following is ok (but don’t think so):
THE FOLLOWING IS PSEUDO CODE THAT YOU SHOULD HELP ME EXPRESS IN A CORRECT SYNTAX
switch(TemplateType){
case signed: ...;
case unsigned: ...;
default: ...;
}
My questions are two:
- is bit depth calculation correct?
- is the
switch-casestatement a good idea? (if yes can you please correct the syntax)
The bit calculation is OK, but can be improved by using
CHAR_BITinstead of8, see this question.To get the other information, you can use
<type_traits>, specifically:std::is_signed/std::is_unsignedstd::is_integral/std::is_floating_pointNote that floating point types are always signed, but
std::is_signedwill return false, because it tests if the type is a signed integer.Also note that
charis just another integral type, so there’s no standard type trait to specifically test that, but you can use a simplestd::is_same<T, char>.In code, this might look like the following:
Live example on Ideone.
Note that
boolcounts as unsigned integer, but that is easily fixed. Also note that the compiler will spew a bunch of warnings regarding “conditional expression is constant”, so that can be improved, but this should suffice as a demonstration.