Skip to content

Instantly share code, notes, and snippets.

@ArthurSonzogni
Last active March 7, 2016 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArthurSonzogni/eb82fd39727924df2249 to your computer and use it in GitHub Desktop.
Save ArthurSonzogni/eb82fd39727924df2249 to your computer and use it in GitHub Desktop.
#ifndef SATURATE_CAST_HPP
#define SATURATE_CAST_HPP
#include <cmath>
// because C++ doesn't allow partial function
// specialization, we must use static method
// from specialized class
//-----------
// EXAMPLE :
//----------
// int v_255 = saturate_cast<float, int>(256.f);
// double pi_d = saturate_cast<double, double>(M_PI);
namespace saturate_cast_detail {
// definition for uint<n>_t
template <typename In, typename Out>
struct F
{
static Out impl(const In& i)
{
return std::max( (In)(0) , std::min( (In)((256<<sizeof(In))-1), i ));
}
};
// specialization for float
template <typename In>
struct F<In,float>
{
static float impl(const In& i)
{
return i;
}
};
// specialization for double
template <typename In>
struct F<In,double>
{
static double impl(const In& i)
{
return i;
}
};
}
template< class In, class Out >
Out saturate_cast(In in) { return saturate_cast_detail::F<In, Out>::impl(in); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment