有什么创造性的方法可以在编译时或至少在使用之前检查字符串是否包含禁止的字符?
Any creative ways of checking if a string contains a forbidden character at compile time or at least before it's used?
我需要一种方法来验证常数字符串在编译时不包含某个字符。我考虑使用static_assert,但要撞到砖墙,因为我正在尝试使用.find方法,这不是恒定的。
我可以选择在类的构造函数中进行检查(实例是上述课程的static const
成员)。
但是,在咬着子弹之前(因为更改构造函数的行为还有其他含义),我想看看其他人是否有一个开箱即用的想法之一,仍然可以完成此操作。<<<<<<<<<</p>
by 常数字符串也许您的意思是a 字符串文字,对于std::string
,无法在常数表达式中使用。
在字符串文字情况下,我们可以利用constexpr
:(实时演示)
template<int N>
constexpr bool has_forbidden_char(const char (&str) [N], char forbidden)
{
for(int i = 0; i < N; ++i)
{
if (str[i] == forbidden)
return true;
}
return false;
}
int main()
{
static_assert(!has_forbidden_char("foobar", 'x'));
static_assert(has_forbidden_char("foobar", 'f'));
}
编辑:迭代到N-1
,如果您假设只会接收字符串文字而不是任意字符数组。通过这种方式,您不会每次检查null字符' 0'。(零长度数组不存在C ,因此不必担心在-1处索引)
//...
for(int i = 0; i < N-1; ++i){ //...
edit2:,由于您使用的是Visual Studio 2015(没有放松的constexpr
功能,因此有可行的C 11符合解决方案:
namespace detail {
template<int N>
constexpr bool has_forbidden_char_help(const char(&str)[N], char forbidden, int index)
{
return (index < N && (str[index] == forbidden || has_forbidden_char_help(str, forbidden, index+1)));
}
} // namespace detail
template<int N>
constexpr bool has_forbidden_char(const char (&str) [N], char forbidden)
{
return detail::has_forbidden_char_help(str, forbidden, 0);
}
int main()
{
static_assert(!has_forbidden_char("foobar", 'x'), "foobar doesn't have x, so this shouldn't fail...");
static_assert(has_forbidden_char("foobar", 'f'), "foobar does have f, so this shouldn't fail...");
}
相关文章:
- 如何检查一个c++字符串中有多少相同的字符/数字
- 在编译时检查字符串文本的长度
- 检查字符串是否"null" C++
- 检查连续对的字符串C++
- 我应该如何解析和检查字符串?
- 检查字符串是否为整数
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 如何检查模板类中的变量是否为字符串类型?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 字符串变成链表,然后检查括号余额
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串中是否有重复的负号?例如 --1
- 如何检查字符串是否正确以将其转换为 int?
- 字符串检查总是返回假的Palidrome
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 是否可以使用字符串检查预处理器定义
- NULL /空字符串检查:CPU开销
- 使用数组和无指针创建回文字符串检查器C++
- 使用constexpr进行基本编译时格式字符串检查