This program
#include <iostream>
#include <locale>
int main () {
std::isxdigit(std::cin.peek(), std::cin.getloc());
}
throws an exception of type std::bad_cast
on me when compiled with gcc or clang using libstdc++. It runs normally with VS2010.
I understand what's going on here. peek()
returns an int
to accommodate the out-of-band EOF value. The locales are not required to have ctype<int>
facet (they do have this facet in VS, perhaps as an extension). If the locale has no facet to perform a function, it will throw a bad_cast
.
But shouldn't this be working according to the spirit of the original <ctype.h>
? Is this a defect in the standard? Is there a commonly-accepted workaround? I know I can check for EOF myself and cast to the relevant character type, but I'd rather not reinvent the wheel.
No: The character type has to be known (assume a 32 bit int is a character type having a 64 bit representation for EOF). It can not be resolved, a locale is not bounded to a specific character type, but it's facets are.
Having:
std::isxdigit<char>(std::cin.peek(), std::cin.getloc());
will clarify the call and (!) ignore EOF making it char(int(-1)).
Hence you might check for EOF yourself.