Просто маленький предикат:
#include <limits>
template <typename T, typename U>
struct can_fit
{
static const bool value = std::numeric_limits<T>::digits
<= std::numeric_limits<U>::digits;
};
#include <iostream>
int main(void)
{
std::cout << std::boolalpha;
std::cout << can_fit<short, float>::value << std::endl;
std::cout << can_fit<int, float>::value << std::endl;
std::cout << can_fit<int, double>::value << std::endl;
std::cout << can_fit<long long, double>::value << std::endl;
std::cout << can_fit<short, int>::value << std::endl;
std::cout << can_fit<int, short>::value << std::endl;
}
Проверяет, существует ли двоичная точность, доступная в T
, в U
. Работает на всех типах.
"Boostified":
// this is just stuff I use
#include <boost/type_traits/integral_constant.hpp>
template <bool B>
struct bool_type : boost::integral_constant<bool, B>
{
static const bool value = B;
};
typedef const boost::true_type& true_tag;
typedef const boost::false_type& false_tag;
// can_fit type traits
#include <limits>
namespace detail
{
template <typename T, typename U>
struct can_fit
{
static const bool value = std::numeric_limits<T>::digits
<= std::numeric_limits<U>::digits;
};
}
template <typename T, typename U>
struct can_fit : bool_type<detail::can_fit<T, U>::value>
{
typedef T type1;
typedef U type2;
static const bool value = detail::can_fit<T, U>::value;
};
// test
#include <iostream>
namespace detail
{
void foo(true_tag)
{
std::cout << "T fits in U" << std::endl;
}
void foo(false_tag)
{
std::cout << "T does not fit in U" << std::endl;
}
}
// just an example
template <typename T, typename U>
void foo(void)
{
detail::foo(can_fit<T, U>());
}
int main(void)
{
foo<int, double>();
}