I need a way to validate that a constant string doesn't contain a certain character at compile time. I thought about using static_assert, but hit a brick wall because I was trying using the .find method, which is not constant.
I have an option of doing the check in the constructor of the class (instances are static const
members of the said class).
But before biting the bullet (since changing the constructor behavior has other implications), I'd like to see if anyone else has one of those creative out-of-the-box ideas to still get this done, preferably at compile time.
By constant string perhaps you mean a string literal, for
std::string
can not be used in a constant expression.In the string literal case we can take advantage of
constexpr
: (Live Demo)Edit: iterate to
N-1
if you assume you will only receive string literals and not arbitrary character arrays. In this way you won't be checking the NULL character '\0' each time. (zero-length arrays do not exist in C++, so no worry about indexing at -1)Edit2: Since you're using Visual Studio 2015, which doesn't have relaxed
constexpr
functionality, here's a C++11 conforming solution that works: