Question

I want to check whether a given char is a digit at compile time. In particular I need the implementation of the following function prototype:

template<char c>
constexpr bool IsDigit();

For clarification: I dont must use a custom implementation. If there is already a built-in way in the std, I would prefer that method.

Was it helpful?

Solution

This should work for ASCII:

constexpr bool IsDigit(char c) { return c >= '0' && c <= '9'; }  // ASCII only

If you need to keep your prototype:

template<char C>
constexpr bool IsDigit() { return C >= '0' && C <= '9'; }  // ASCII only

For wchar_t support you could try something like:

constexpr bool IsDigit(wchar_t c)
{
  return (c >= L'0' && c <= L'9') ||
         (c >= L'\u0660' && c <= L'\u0669') ||  // Arabic-Indic
         (c >= L'\u06F0' && c <= L'\u06F9') ||  // Extended Arabic-Indic
         (c >= L'\u07C0' && c <= L'\u07C9') ||  // NKO
         (c >= L'\u0966' && c <= L'\u096F') ||  // Devanagari
         (c >= L'\u09E6' && c <= L'\u09EF') ||  // Bengali
         (c >= L'\u0A66' && c <= L'\u0A6F') ||  // Gurmukhi
         (c >= L'\u0AE6' && c <= L'\u0AEF') ||  // Gujarati
         (c >= L'\u0B66' && c <= L'\u0B6F') ||  // Oriya
         (c >= L'\u0BE6' && c <= L'\u0BEF') ||  // Tamil
         (c >= L'\u0C66' && c <= L'\u0C6F') ||  // Telugu
         (c >= L'\u0CE6' && c <= L'\u0CEF') ||  // Kannada
         (c >= L'\u0D66' && c <= L'\u0D6F') ||  // Malayalam
         (c >= L'\u0E50' && c <= L'\u0E59') ||  // Thai
         (c >= L'\u0ED0' && c <= L'\u0ED9') ||  // Lao
         (c >= L'\u0F20' && c <= L'\u0F29');    // Tibetan

  // Missing check for Myanmar, Khmer, Mongolian, Limbu, New Tai Lue,
  // Tai Tham Hora, Tai Tham Tham, Balinese, Sundanese, Lepcha, Ol Chiki,
  // Vai, Surashtra, Kayah, Javanese, Cham, Meetei Mayek, Osmanya, Brahmi,
  // Sora, Chakma, Sharada, Takri, Mathematical.
  // For codes see http://www.unicode.org/ucd/
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top