c++11 乱模版

发布时间 2023-12-15 16:16:25作者: lxg_7105
std::is_same,std::enable_if,std::is_integral
template<typename T>
bool isZero(T v)
{
    if (std::is_same<T, float>::value)
    {
        return (fabs(v) < FLT_EPSILON);
    }
    else  if (std::is_same<T, double>::value)
    {
        return (fabs(v) < DBL_EPSILON);
    }

    return v == 0;
}

template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type 
Foo1(T t)
{
    qDebug() << "Foo1: float";
    return t;
}

template<typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
Foo1(T t)
{
    qDebug() << "Fool: int";
    return t;
}
template<typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
IsOdd(T i)
{
    return i % 2;
}

template<typename T, typename T1 = typename std::enable_if<std::is_integral<T>::value>::type>
bool IsEven(T i)
{
    return !bool(i % 2);
}
自定义c++模版函数
namespace cpp 
{
    template<class T, class U>
    struct is_same {
        static constexpr bool value = false;
    };

    template<class T>
    struct is_same<T, T> {
        static constexpr bool value = true;
    };
    template<class T, class U>
    constexpr bool is_same_v = is_same<T, U>::value;


    template<class T>
    struct integral_const {
        using type = T;
    };
    template<class T>
    struct remove_reference : integral_const<T> {};

    template<class T>
    struct remove_reference<T&> : integral_const<T> {};

    template<class T>
    using remove_reference_t = typename remove_reference<T>::type;
    template<class T>
    struct remove_const : integral_const<T> {};

    template<class T>
    struct remove_const<const T> : integral_const<T> {};

	template<class T>
	using remove_const_t = typename remove_const<T>::type;
}
工厂模版
template<typename T>
class GFactory
{
public:
    template<typename... Args>
    static T* Create(Args&&... args)
    {
        return new T(std::forward<Args>(args)...);
    }
};