Last active
March 7, 2016 09:51
-
-
Save ArthurSonzogni/eb82fd39727924df2249 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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