Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kikairoya
Created November 10, 2010 08:34
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 kikairoya/670552 to your computer and use it in GitHub Desktop.
Save kikairoya/670552 to your computer and use it in GitHub Desktop.
#include <cstddef>
#include <iostream>
namespace cts { // compile time string
using std::size_t;
template <size_t From, typename charT, size_t N1, size_t N2>
struct eq_helper {
static constexpr int exec(const charT (&s1)[N1], const charT (&s2)[N2]) {
return s1[From]<s2[From] ? -1 : s2[From]<s1[From] ? 1 : eq_helper<From+1, charT, N1, N2>::exec(s1, s2);
}
};
template <typename charT, size_t N>
struct eq_helper<N, charT, N, N> {
static constexpr int exec(const charT (&)[N], const charT (&s2)[N]) { return 0; }
};
template <typename charT, size_t N1, size_t N2>
struct eq_helper<N1, charT, N1, N2> {
static constexpr int exec(const charT (&)[N1], const charT (&s2)[N2]) { return 1; }
};
template <typename charT, size_t N1, size_t N2>
struct eq_helper<N2, charT, N1, N2> {
static constexpr int exec(const charT (&)[N1], const charT (&s2)[N2]) { return -1; }
};
template <typename charT, size_t N1, size_t N2>
constexpr int compare(const charT (&s1)[N1], const charT (&s2)[N2]) {
return eq_helper<0, charT, N1, N2>::exec(s1, s2);
}
}
int main()
{
std::cout << std::integral_constant<int, cts::compare("aaa", "aaa")>::value << '\n';
std::cout << std::integral_constant<int, cts::compare("aaa", "bbb")>::value << '\n';
std::cout << std::integral_constant<int, cts::compare("aaa", "aa")>::value << '\n';
std::cout << std::integral_constant<int, cts::compare("aaa", "aaaa")>::value << '\n';
std::cout << std::integral_constant<int, cts::compare("ccc", "bbb")>::value << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment