Tuesday, November 16, 2010

Compile-time size determination

WARNING ugly hack ahead! WARNING

I have a project that has two components, written in two languages, that execute in two different execution environments (PPU and SPU). One component is written in C++ and the other in assembly and since data is passed back and forth fairly regularly the C++ component has a ton of static assertions validating structure size and offsets in the hope that if anything breaks it is caught early.

Finding initial, or updating existing, structure offsets and sizes was tedious. Using printf() worked but the whole project would have to build, it'd be better if it would just fail at compile time with the numbers I needed. Oh, hey, templates might actually work here...

Say, I had:

struct Foo {
// some number of fields here
};

Then:

template
struct fail
{
enum { value = a / 0 };
};
fail f1;

Would give me both this:

test.cpp:13: warning: division by zero in 'a / 0'
test.cpp: In instantiation of 'fail<136u>':

... and a slightly dirty feeling.

(Blogspot still sucks for posting code.)

No comments:

Post a Comment