C++11 has two new character integral data types, char16_t and char32_t. I would like to emulate them for compilers that don’t have a distinct type in order to overload I/O operations to see them a characters instead of their integer value.
These are the requirements:
- Distinct (no
typedef). - exact-width on normal systems (ala uint16_t and uint32_t)
- other C++11 features are allowed (see below first attempt)
- Must play nice with literals;
char16_t c16 = u"blabla unicode text blabla";must work. - if char16_t can be used in math operators, obviously this needs to function as well.
My first attempt which fails in the literal department was a strongly typed enum:
enum char16_t : uint16_t;
This has other drawbacks as well, that could perhaps be resolved by supplying the necessary operators myself (which is really fine by me).
I don’t think you will get the initialization to work because there isn’t much scope to get it to work. The problem is that the initialization you are using in your example isn’t supposed to work: the string literal
u"..."yields an an array ofchar16_t constobjects and you want to initialize a pointer with it:Also, without implementation of
char16_tin the compiler it is very unlikely to supportchar16_tstring literals. The best you could achieve is to play macro tricks which are intended to do the Right Thing. For now, you’d use e.g. wide character literals and when you get a compiler which supportchar16_tyou just change the macro to usechar16_tliterals. Even for this to work you might need to use a record type which is bigger than 16 bit becausewchar_tuses 32 bits on some platforms.Obviously, you still need to provide all kinds of operators e.g. to make integer arithmetic and suitable conversions work.