如果您想将getRatio() 函数限制为仅用于int, long, double and float,那么您也可以使用此函数。如果您使用 char 类型参数调用它,它将产生“有意义的”编译错误。编译错误将是:this_type_is_not_allowed_in_getRatio。
//yourheader.h
template<typename T>
inline T getRatio(T numer, T denom)
{
typedef typelist<int, typelist<long, typelist<double, float>>> allowedtypes;
compile_time_checker<contains<allowedtypes, T>::result> this_type_is_not_allowed_in_getRatio;
return (numer/denom);
}
它使用这个标题:
//metafunctions.h
template<typename H, typename T>
struct typelist
{
typedef H Head;
typedef T Tail;
};
template<typename T, typename Tail>
struct contains
{
static const bool result = false;
};
template<typename Head, typename Tail, typename T>
struct contains<typelist<Head, Tail>, T>
{
static const bool result = false || contains<Tail, T>::result;
};
template<typename T, typename Tail>
struct contains<typelist<T, Tail>, T>
{
static const bool result = true || contains<Tail, T>::result;
};
template<bool b> struct compile_time_checker;
template<> struct compile_time_checker<true> {};
希望对您有所帮助。 您现在可以在一个函数中编写所有代码!