我想在编译时检查我的字符串文字的长度。目前我正在考虑以下构造,但无法完成:
#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!"
}
最佳答案
这是 C++,其中有比宏更高级的选项。模板可以为您提供您想要的确切语义。
template<std::size_t N>
constexpr auto& STR(char const (&s)[N]) {
static_assert(N < 10, "String exceeds 10 bytes!");
// < 11 if you meant 10 characters. There is a trailing `\0`
// in every literal, even if we don't explicitly specify it
return s;
}
数组引用参数将绑定(bind)到字符串字面值,而不是指针(指针可能会触发您的宏),推断出它们的大小,并在函数体中执行检查。然后,如果一切都检查完毕,它将返回未更改的引用,甚至允许继续进行重载解析。
关于c++ - 在编译时检查字符串文字的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52852503/