101. 整数型に関するテンプレート(オリジナル)

101.1 符号付き整数型から符号無し整数型を得る。

次のメタ関数は、符号付き整数型を指定した場合に対応する符号無し整数型を返します。符号付き整数型以外を指定した場合、または対応する符号無し整数型がない場合はそのままの型を返します。

template<class T>
struct to_unsigned
{
  typedef T type;
};

template<>
struct to_unsigned<signed char>
{
  typedef unsigned char type;
};

template<>
struct to_unsigned<short>
{
  typedef unsigned short type;
};

template<>
struct to_unsigned<int>
{
  typedef unsigned int type;
};

template<>
struct to_unsigned<long>
{
  typedef unsigned long type;
};

long long 型など、処理系が独自の型をサポートする場合には、それらについてもテンプレートを特殊化する必要があります。また、char 型や wchar_t 型が符号付きの場合に変換するのであれば、それらの特殊化も必要になります。

なお、符号無し整数型から符号付き整数型を得るための to_signed メタ関数も同じようにして定義できますので、是非試してみてください。

このエントリーを含むはてなブックマーク