Skip to content

Instantly share code, notes, and snippets.

@RicoP
Created July 11, 2018 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicoP/f521536339581bca660b9abe9396131e to your computer and use it in GitHub Desktop.
Save RicoP/f521536339581bca660b9abe9396131e to your computer and use it in GitHub Desktop.
check string equality with const expressions [c++11]
constexpr bool constStringEquals(const char * lhs, const char * rhs) {
return (*lhs) != (*rhs)
? false
: ((*lhs) == 0
? true
: constStringEquals(lhs + 1, rhs + 1)
);
}
constexpr bool constStringEndsWith(const char * str, const char * suffix) {
return constStringEquals(str, suffix)
? true
: ((*str) == 0
? false
: constStringEndsWith(str+1, suffix)
);
}
#define STATIC_ASSERT(EXPR) static_assert(EXPR, #EXPR)
STATIC_ASSERT(!constStringEquals("HELLO", "WORLD"));
STATIC_ASSERT(constStringEquals("HELLO", "HELLO"));
STATIC_ASSERT(!constStringEquals("HELLO", "HELLOHELLO"));
STATIC_ASSERT(!constStringEquals("HELLOHELLO", "HELLO"));
STATIC_ASSERT(!constStringEquals("", "WORLD"));
STATIC_ASSERT(!constStringEquals("HELLO", ""));
STATIC_ASSERT(constStringEquals("", ""));
STATIC_ASSERT(!constStringEndsWith("HELLO", "WORLD"));
STATIC_ASSERT(constStringEndsWith("HELLO", "HELLO"));
STATIC_ASSERT(!constStringEndsWith("HELLO", "HELLOHELLO"));
STATIC_ASSERT(constStringEndsWith("HELLOHELLO", "HELLO"));
STATIC_ASSERT(!constStringEndsWith("", "WORLD"));
STATIC_ASSERT(constStringEndsWith("HELLO", ""));
STATIC_ASSERT(constStringEndsWith("", ""));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment