minor optimization: minimize calls to end()
Minor optimization: increase the chances that the compiler will inline calls to end().
Has been observed to make a difference with gcc 4.9.3.
Fix build and warnings on MSVC (2017)
Uses static_assert, a C++11 feature. Also adds some explicit uses of
static_cast in order to suppress warnings about lossy type conversion.