ghostmansd
ghostmansd

Reputation: 3465

C++: fixed-size integer implementation for charX_t types

It is known to me that new character types were introduced in C++11. However, since C++11 is not available everywhere, it may be necessary to introduce char16_t and char32_t for everyone who wishes to work with UTF-16 and UTF-32. I've tried to implement such types. Here is a basic variant of the working implementation compiled with g++ and clang++. For simplicity I use typedef for uint8_t, but it works with other types too.

template <typename CLASS>
class basechar
{
private:
  CLASS self;
public:
  ~basechar()
  {}

  basechar()
  : self(0) {}

  basechar(const CLASS& object)
  : self(object) {}

  inline operator CLASS() const
  { return self; }

  friend std::ostream&
  operator<<(std::ostream& sstream, const basechar<CLASS>& object)
  { sstream << (uint32_t)(uint8_t)(object.self); return sstream; }
};

int main()
{
  typedef basechar<uint8_t> bchar;
  const char* array = "AZbyCX";
  const bchar* barray = reinterpret_cast<const bchar*>(array);
  for (size_t i = 0; i < 4; ++i)
  {
    std::cout << (uint32_t)(uint8_t)array[i] << std::endl;
    std::cout << barray[i] << std::endl;
  }
  return 0;
}

It prints exactly what I expect:

65
65
90
90
98
98
121
121

Since it may be not well-defined behaviour, I'd like to ask: is it possible to implement such feature portable over different compilers? I want to be able to overload in functions both uint16_t and mychar16_t types.

Thank you very much!

Upvotes: 0

Views: 92

Answers (0)

Related Questions