Is it possible to determine the size of a C++ class at compile-time?
I seem to remember a template meta-programming method, but I could be mistaken...
sorry for not being clearer - I want the size to be printed in the build output window
Is it possible to determine the size of a C++ class at compile-time?
I seem to remember a template meta-programming method, but I could be mistaken...
sorry for not being clearer - I want the size to be printed in the build output window
If you really need to to get sizeof(X) in the compiler output, you can use it as a parameter for an incomplete template type:
template<int s> struct Wow;
struct foo {
int a,b;
};
Wow<sizeof(foo)> wow;
$ g++ -c test.cpp
test.cpp:5: error: aggregate ‘Wow<8> wow’ has incomplete type and cannot be defined
To answer the updated question -- this may be overkill, but it will print out the sizes of your classes at compile time. There is an undocumented command-line switch in the Visual C++ compiler which will display the complete layouts of classes, including their sizes:
That switch is /d1reportSingleClassLayoutXXX, where XXX performs substring matches against the class name.
Whats wrong with sizeof? This should work on objects and classes.
void foo( bar* b )
{
int i = sizeof bar;
int j = sizeof *b;
// please remember, that not always i==j !!!
}
Edit:
This is the example I was thinking of, but for some reason it's not working. Can anyone tell me what's wrong?
#include <iostream>
using namespace std;
class bar {
public: int i;
bar( int ii ) { i = ii; }
virtual ~bar(){ i = 0; }
virtual void d() = 0;
};
class bar2: public bar {
public: long long j;
bar2( int ii, long long jj ):bar(ii){ j=jj; }
~bar2() { j = 0; }
virtual void d() { cout << "virtual" << endl; };
};
void foo( bar *b )
{
int i = sizeof (bar);
int j = sizeof *b;
cout << "Size of bar = " << i << endl;
cout << "Size of *b = " << j << endl;
b->d();
}
int main( int arcc, char *argv[] )
{
bar2 *b = new bar2( 100, 200 );
foo( b );
delete b;
return 0;
}
The application been run on linux (gcc 4.4.2):
[elcuco@pinky ~/tmp] ./sizeof_test
Size of bar = 8
Size of *b = 8
virtual
sizeof() determines the size at compile time.
It doesn't work until compile time, so you can't use it with the preprocessor.
There is operator sizeof( int ), sizeof( char ) so I think that it is possible and call probably look like sizeof( MyClass )
I developed a tool, named compile-time printer, to output values and types during compilation.
You can try it online under: https://viatorus.github.io/compile-time-printer/
The repository can be found here: https://github.com/Viatorus/compile-time-printer
To get the size of any type as output would be:
constexpr auto unused = ctp::print(sizeof(YourType));