samedi 3 novembre 2018

static_assert in a macro but also expand to something that can be used as a function parameter

For instance. I have the macro CHARCOUNT(x) that expands to sizeof(x)/sizeof(x[0]). I would like to use static_assert to ensure each macro expansion does a check to see if the result is greater than 2 to avoid someone passing in a pointer to a string and not pointer to an array of characters.

I would like something like this static assert:

static_assert(x) > 2

This macro would be used to ensure that string copies don't exceed the buffer size such as:

TCHAR szMyStr[10];
_tcscpy_s(szMyStr, CHARCOUNT(szMyStr), L"My result");

If someone accidentally passes in a pointer where CHARCOUNT would result in the length of the pointer to the string instead of the number of bytes I would like an assert at compile time.

const TCHAR* myChars = L"My result";
auto len = CHARCOUNT(myChars);

The CHARCOUNT above should result in a compile time assert. Any pointers would be helpful.

Aucun commentaire:

Enregistrer un commentaire