1.8 整数除算で端数切り上げ(商+剰余)

ちょっと強引ですが、整数除算で端数を切り上げた商と剰余を求める関数テンプレートです。long long 型等、標準でサポートされていない型に対応するには、それぞれ個別に特殊化してあげる必要があります。

template<class T>
struct xdiv_t
{
  typedef std::div_t type;
private:
  typedef std::numeric_limits<T> l;
  BOOST_STATIC_ASSERT(l::is_integer && l::is_signed);
};

template<>
struct xdiv_t<long>
{
  typedef std::ldiv_t type;
};

template<class T>
typename xdiv_t<T>::type ceil_with_rem(T dividend, T divisor)
{
  assert(divisor > 0);
  typename xdiv_t<T>::type result = std::div(dividend, divisor);
  if (result.rem > 0)
  {
    result.rem -= divisor;
    ++result.quot;
  }
  return result;
}

以下はその整数定数版です。

template<long L, long R>
struct iceil_with_rem
{
  static const long quot = (L < 0 ? -(-L / R) : (L + R - 1) / R);
  static const long rem = L - quot * R;
private:
  BOOST_STATIC_ASSERT(R > 0);
};


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