I have a global include file which contains a set of structures. Somewhere in my program, I have a class that contains a member array. The number of elements in this array is dependent on the size 开发者_如何学Pythonof a specific field in a specific struct. I want to make it so that the array size will get automatically updated if the sizeof the structure field is changed. I have been able to do this succesfully with the following expression:
bool shadowChkBox[sizeof(FSCconfigType::WriteEn)*8*MAX_FSCS];
FSCconfigType is the struct type and WriteEn is one of the fields. Now this worked but only on ubuntu. On RHEL 5, the compiler declared it as an error. What other alternatives could I have for doing this? I am working with Qt.
Here is one possible answer:
#include <iostream>
struct A
{
int a;
int b;
int c;
};
bool items[sizeof(reinterpret_cast<A *>(0)->b)];
int main()
{
std::cout << sizeof(reinterpret_cast<A *>(0)->b) << ",";
std::cout << sizeof(items) << std::endl;
return 0;
}
One fragile answer is to take the difference of the offsetof values for WriteEn and the next field up (or failing that, the sizeof the whole struct).
This may give a slightly larger answer than sizeof due to alignment-based padding.
A bigger problem is what happens if you rearrange your fields without fixing this - but it might be an option if you're desperate.
#include <iostream>
struct C
{
int iv;
void* pv;
char buf[128];
};
template< typename TObj, typename TFieldType >
std::size_t field_size( TFieldType (TObj::*) )
{
return sizeof(TFieldType);
}
int main() {
std::cout << field_size(&C::iv) << std::endl;
std::cout << field_size(&C::pv) << std::endl;
std::cout << field_size(&C::buf) << std::endl;
}
精彩评论