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
にあなたが唯一の文字列リテラルではなく、任意の文字配列を受け取りますと仮定した場合、我々はconstexpr
を利用することができ、文字列リテラルの場合
。このようにして、毎回NULL文字 '\ 0'をチェックすることはありません。 (長さゼロの配列は、C++での-1インデックスそんなに心配は存在しません)
//...
for(int i = 0; i < N-1; ++i){ //...
EDIT2:あなたはリラックスしたconstexpr
を持っていないのVisual Studio 2015を使用しているので、ここでは動作する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-リテラル文字列からconstexpr関数を使用できます。 Gccにも拡張がありますので、リテラル文字列でudlを許可します。 – Jarod42
Spot on!私はそれを働かせることができた。私は以下の@AndyGの回答はもっと読みやすく(他の人を助ける答えとしてマークしています)、これが私の助けを借りてできたものです: –