Reputation: 5201
I'm looking for a typetrait able to know if the range of a type is included in another. A typetrait where is_included_in<T,U>::value
is true
when each value of type T
can be stored as a value of type U
. Example :
is_included_in<float,double>::value; // true
is_included_in<double,float>::value; // false
is_included_in<int,double>::value; // true
is_included_in<bool,long int>::value; // true
is_included_in<long long int,float>::value; // false
Is there somthing in Boost able to do this ? Or have I to write it myself ?
Note: I don't use C++11 for compatibility reason.
Upvotes: 1
Views: 102
Reputation: 23497
For fundamental integral and floating-point types, you can compare their number of digits as follows:
template <typename T, typename U>
struct is_included_in
: boost::integral_constant<bool,
std::numeric_limits<T>::digits <= std::numeric_limits<U>::digits> { };
It works for all you exemplary cases. The only problem is that it yields true
for, e.g., <float, long>
. A partial specialization helps here:
template <typename T, typename U,
bool = boost::is_floating_point<T>::value && boost::is_integral<U>::value>
struct is_included_in
: boost::integral_constant<bool,
std::numeric_limits<T>::digits <= std::numeric_limits<U>::digits> { };
template <typename T, typename U>
struct is_included_in<T, U, true> : boost::false_type { };
Live demo: https://wandbox.org/permlink/NBXFOUK8fX9sxyfm.
Upvotes: 1
Reputation: 385144
No, you'd have to make it yourself.
That being said, if you want to use this to make arithmetic conversions value-safe, Boost already has numeric_cast
that achieves this.
So, depending on your goal, you may not need a trait.
At the very least you could probably examine the numeric_cast
implementation and use its principles to build your own trait(s).
Upvotes: 2