有什么创造性的方法可以在编译时或至少在使用之前检查字符串是否包含禁止的字符?

Any creative ways of checking if a string contains a forbidden character at compile time or at least before it's used?

本文关键字:字符串 检查 是否 字符 禁止 包含 方法 创造性 什么 编译      更新时间:2023-10-16

我需要一种方法来验证常数字符串在编译时不包含某个字符。我考虑使用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...");
}