我想在编译时检查我的字符串文字的长度.现在我正在考虑以下构造,但无法完成它:
#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!"
}
Run Code Online (Sandbox Code Playgroud)
Sto*_*ica 14
这是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;
}
Run Code Online (Sandbox Code Playgroud)
数组引用参数将绑定到字符串文字,而不是指针(可以使宏跳闸),推断它们的大小,并在函数体中执行检查.然后,如果所有内容都检出,它将返回引用,即使是持续的重载分辨率.
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |