Ho sviluppato alcune macro che consentono effettivamente di utilizzare sizeof all'interno di una condizione macro. Sono in un file di intestazione che ho caricato here (licenza MIT).
Esso consentirà di codice come questo:
#include <iostream>
#include "SIZEOF_definitions.h"
//You can also use SIZEOF_UINT in place of SIZEOF(unsigned, int)
// and UINT_BIT in place of SIZEOF_BIT(unsigned, int)
#if SIZEOF(unsigned, int) == 4
int func() { return SIZEOF_BIT(unsigned, int); }
#elif SIZEOF(unsigned, int) == 8
int func() { return 2 * SIZEOF_BIT(unsigned, int); }
#endif
int main(int argc, char** argv) {
std::cout SIZEOF(unsigned, long, int) << " chars, #bits = " << SIZEOF_BIT(unsigned, long, int) << '\n'
<< SIZEOF(unsigned, int) << " chars, #bits = " << SIZEOF_BIT(unsigned, int) << '\n'
<< SIZEOF(int) << " chars, #bits = " << SIZEOF_BIT(int) << '\n';
std::cout << func() << std::endl;
return 0;
}
Nota le virgole all'interno SIZEOF(unsigned, long, int)
.
fonte
2017-05-26 22:00:33
Ho appreso che le affermazioni in fase di costruzione sono possibili, grazie alla tua domanda. Questa tecnica è discussa in dettaglio in questo thread: http://stackoverflow.com/questions/174356/ways-to-assert-expressions-at-build-time-in-c – nagul