简体   繁体   English

static_assert在宏中,但也可以扩展为可用作函数参数的内容

[英]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]) . 我有宏CHARCOUNT(x)扩展为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. 我想使用static_assert来确保每个宏扩展都进行检查以查看结果是否大于2,以避免有人传递指向字符串的指针而不是指向字符数组的指针。

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. 如果有人不小心传入了一个指针,其中CHARCOUNT将导致指向字符串的指针的长度而不是字节数,那么我希望在编译时声明一个断言。

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

The CHARCOUNT above should result in a compile time assert. 上面的CHARCOUNT应该导致一个编译时断言。 Any pointers would be helpful. 任何指针都会有所帮助。

You should be using std::extent instead of that macro, which gives you 0 for unsupported types (eg arrays without bounds, non-array types). 您应该使用std::extent而不是该宏,它为不支持的类型(例如,无边界的数组,非数组类型)提供0。

For your use case a constexpr function that gives you the size for an array variable would be better suited, like so: 对于您的用例,使用constexpr函数为您提供数组变量的大小会更合适,例如:

template <typename T, std::size_t N>
constexpr std::size_t arrsize(T (&)[N]) {
    return N;
}

Then you don't need to assert on the size since you can only use the function with actual arrays. 然后,您无需声明大小,因为您只能将函数与实际数组一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM