Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using char16_t, char32_t etc without C++ 11?

Tags:

c++

c++11

I would like to have fixed width types including character types. <stdint.h> provides types for integers, but not characters, unless when using C++11, which i can't do.

Is there a clean way to define these types (char16_t, char32_t, etc) without conflicting with those defined by C++11 in case the source would ever be mixed with C++11 ?

Thank you :)

like image 793
Virus721 Avatar asked Mar 17 '23 06:03

Virus721


1 Answers

Checking whether this types are supported is a platform-dependent thing, I think. For example, GCC defines: __CHAR16_TYPE__ and __CHAR32_TYPE__ if these types are provided (requires either ISO C11 or C++ 11 support).

However, you cannot check for their presence directly, because they are fundamental types, not macros:

In C++, char16_t and char32_t are fundamental types (and thus this header does not define such macros in C++).

However, you could check for C++ 11 support. According to Bjarne Stroustrup's page:

__cplusplus

In C++11 the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

So, basically, you could do:

#if __cplusplus > 199711L
// Has C++ 11, so we can assume presence of `char16_t` and `char32_t`
#else
// No C++ 11 support, define our own
#endif

How define your own?

-> MSVC, ICC on Windows: use platform-specific types, supported in VS .NET 2003 and newer:

typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;

-> GCC, MinGW, ICC on Linux: these have full C99 support, so use types from <cstdint> and don't typedef your own (you may want to check version or compiler-specific macro).

And then:

typedef int16_t char16_t;
typedef uint16_t uchar16_t;
typedef int32_t char32_t;
typedef uint32_t uchar32_t;

How to check what compiler is in use? Use this great page ('Compilers' section).

like image 198
Mateusz Grzejek Avatar answered Apr 19 '23 10:04

Mateusz Grzejek