AudioPlastic

C++ Palindrome Detection at Compile Time

| Comments

I made a brief blog post a couple of years ago showing how to do palindrome detection in C++ using a reverse itterator. I recently stumbled across a recursive plaindrome detection algorithm on stack overflow. The author explicitly noted that it would be more efficient to do palindrome detection using a loop, but then I thought this was an ideal candidate for compile-time evaluation using the nifty C++11 constexpr declaration.

1
2
3
4
5
6
7
8
9
constexpr bool compileTimeIsPalindrome(const char* s, int len)
{
    return len < 2 ? true : s[0] == s[len-1] && compileTimeIsPalindrome(&s[1], len-2);
}

int main()
{
	static_assert( compileTimeIsPalindrome((char *)"1991", 4), "the only assertion" );
}

No runtime overhead. Happy days.

Comments