1 Replies - 1987 Views - Last Post: 17 December 2011 - 05:06 PM

#1 MathiasVP  Icon User is offline

  • D.I.C Head

Reputation: 27
  • View blog
  • Posts: 154
  • Joined: 08-August 10

typeid operator and bitfield in structs

Posted 17 December 2011 - 08:39 AM

Hey everyone. I did some experiments with bitfields the other day and noticed something that I wasn't quite able to explain. Conside the code:

#include <iostream>

template<typename T>
struct varType {
	//Maximize number of bits
	long long t : sizeof(T)*8;

int main()
	//Create struct with 8 bits
	varType<signed char> foo = {42};
	std::cout << "Type of foo:\t" << typeid(foo).name() << std::endl;
	std::cout << "Type of foo.t:\t" << typeid(foo.t).name() << std::endl;
	return 0;

To me it would make sense that typeid(foo).name() would output "struct varType<__int64>" since typeid(foo.t).name() outputs __int64, but that's not the code. Actually the output is:

Type of foo:   struct varType<signed char>
Type of foo.t: __int64

Can anyone explain why typeid(foo).name() outputs the type as a struct containing a signed char (which matches the number of bits), but the actual type (foo.t) is outputted as __int64, which is what it is declared at?

Thank you in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: typeid operator and bitfield in structs

#2 Karel-Lodewijk  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Re: typeid operator and bitfield in structs

Posted 17 December 2011 - 05:06 PM

First of all the name function of a typeid is mainly there for debugging purpose really. It returns some sort of a description for a type. What it returns exactly is implementation specific. For example for me your program prints:

Type of foo:	7varTypeIaE
Type of foo.t:	a

That being said typeid(foo).name() returns "struct varType<signed char>" because you declare it to be one on line 12. It doesn't appear to print anything about the contents of the struct.

Foo.t is a long long as you declare it on line 6, but a long long (on your system at least) is the same as an __int64.

The bitfield part is in this case irrelevant.

This post has been edited by Karel-Lodewijk: 17 December 2011 - 05:07 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1