如果你不能使用 boost,你别无选择,只能自己实现一些类型特征机制。这可能有点乏味,但您可以这样做:
// convinience base classes
template<typename T, T Value>
struct constant { static const T value = Value; };
typedef constant<bool, true> true_type;
typedef constant<bool, false> false_type;
// a trait to check if two types are the same
template<typename T, typename U>
struct is_same : false_type {};
template<typename T>
struct is_same<T,T> : true_type{};
// a trait to check if type is integral, based on is_same
// it's missing wchar_t and bool
#define SAME(T,U) is_same<T,U>::value
template<typename T>
struct is_integral : constant<bool,SAME(T,char) ||
SAME(T,signed char) ||
SAME(T,unsigned char) ||
SAME(T,short) ||
SAME(T,unsigned short) ||
SAME(T,int) ||
SAME(T,unsigned int) ||
SAME(T,long) ||
SAME(T,unsigned long) ||
SAME(T,long long) ||
SAME(T,unsigned long long)> {};
// Trait class to change a type to its unsigned variant.
// The base template simply forwards the type, specializations do the work.
template<typename T>
struct identity { typedef T type; };
template<typename T>
struct make_unsigned : identity<T> {};
template<> struct make_unsigned<signed char> : identity<unsigned char>{};
template<> struct make_unsigned<short> : identity<unsigned short>{};
template<> struct make_unsigned<int> : identity<unsigned int>{};
template<> struct make_unsigned<long> : identity<unsigned long>{};
template<> struct make_unsigned<long long> : identity<unsigned long long>{};
// Utility class to enable overloads based on some compile time condition
template<bool B, typename = void>
struct enable_if { };
template<typename T>
struct enable_if<true, T> {
typedef T type;
};
// Only enable this function if I is integral
template<typename I>
typename enable_if<is_integral<I>::value>::type MyFunction(I &value)
{
typename make_unsigned<I>::type ui;
}
int main()
{
int i;
MyFunction(i); // ok
float f;
MyFunction(f); // fails
}