我希望在编译时检查我的字符串文字的长度。目前我正在考虑以下结构,但无法完成它:
我想要在编译时检查字符串文字的长度。目前我在考虑下面的结构,但是无法完成它:
#define STR(s) (sizeof(s) < 10 ? s : /* somehow perform static_assert */)
void foo(const char* s) {}
int main() {
foo(STR("abc")); // foo("abc")
foo(STR("abcabcabcabc")); // compile time error: "String exceeds 10 bytes!"
}
#define STR(s) (strlen(s) < 10 ? s : nullptr)
?那么在foo函数内部检查“空值”... - Ruksconst char
数组,然后使用sizeof() -1
。 - Thomas Matthews