在编译时检查字符串文本的长度
Check length of string literal at compile time
我想在编译时检查字符串文字的长度。现在我正在考虑以下构造,但无法完成:
#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 ` `
// in every literal, even if we don't explicitly specify it
return s;
}
数组引用参数将绑定到字符串文本,而不是指针(可能会触发宏(,推断它们的大小,并在函数主体中执行检查。然后,如果所有内容都检出,它将返回引用不变,甚至允许继续解决过载问题。
我会添加到@StoryTeller - 不诽谤莫妮卡伟大的答案, 如果你需要(像我一样(传递字符串的最大长度和参数,你可以将实现扩展为更通用的:
template<const int MAX_LEN, std::size_t N>
constexpr auto& STR(char const (&s)[N])
{
static_assert(N < MAX_LEN, "String overflow!");
return s;
}
如果您需要几个已知长度,您可以使用模板专用化:
template<std::size_t N>
constexpr auto & STR16(char const (&s)[N])
{
return STR<16>(s);
}
第一个函数可以是通用版本,第二个函数可以访问项目的常量。
相关文章:
- 在 C++ 中从 8 位 ASCII 字符创建 7 位 ASCII 文本字符串
- cin>>gender 和 cin>>*gender ( c 样式文本字符串)有什么区别
- 是否可以动态检查文本字符串是否是 C++ 中给定类的成员?
- 用Zlib解压缩文本字符串
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 来自文本字符串或某种其他机制的代码类自动生成器
- 函数读取最大和min int值,并用文本字符串返回
- 模板代码和文本字符串
- 声明具有常量引用与常量变量的常量文本字符串
- 加密给定的文本字符串-Caesar Cipher
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 如何将文本从一个文件复制到另一个文件,然后将文本字符串的第一个字母转换为大写
- 从文本字符串推断类型
- 跟踪内存中的文本字符串
- 将字符串变量与整数和文本字符串连接起来的 C++ 字符串流
- 将 char 数组分配给文本字符串 - C++
- 如何修复将文本字符串附加到 C 字符串的错误
- 使用C++读取不同长度的多个文本字符串
- 在C++中创建原始文本字符串,类似于 C# 的"@ string"