整数/实数类型的模板结构专门化

时间:2013-08-21 17:53:00

标签: c++ templates c++11 sfinae

我想为不同种类的数字(整数,浮点)创建验证器,例如:

typename number_validator<T>::type validator;

我在std中找到了有用的特征,即is_integralis_floating_point。如何使用这些特征来专门化模板number_validator(它是struct)?

编辑: 我正在寻找这样的东西:

template<typename T, typename Enabled>
struct number_validator {};

template<typename T>
struct number_validator<T, typename enable_if<is_floating_point<T>::value, T>::type> 
//this doesn't work..
{
    typedef floating_point_validator type;
};

3 个答案:

答案 0 :(得分:12)

这可能是您正在寻找的,即标签调度

template<typename T, bool = is_integral<T>::value>
struct number_validator {};

template<typename T>
struct number_validator<T, true> 
{
    typedef integral_validator type;
};

template<typename T>
struct number_validator<T, false> 
{
    typedef floating_point_validator type;
};

这假设您确实对数字进行操作,因此类型始终是整数或浮点数。

答案 1 :(得分:1)

在这种情况下你甚至不需要那些,你实际上可以像这样专门化模板。

template <typename T>
struct number_validator;
template <>
struct number_validator<float>;

template <>
struct number_validator<int>;

template <>
struct number_validator<double>;

这将专门针对每种类型的数字验证器,这要求您列出所有积分和浮点类型。你也可以这样做:

#include <type_traits>
#include <iostream>
template<class T>
typename std::enable_if<std::is_floating_point<T>::value,T>::type func(T t) { 
    std::cout << "You got a floating point" << std::endl;
    return t;
}

template<class T>
typename std::enable_if<std::is_integral<T>::value,T>::type func(T t) { 
    std::cout << "You got an Integral" <<std::endl;
    return t;
}

int main() {
    float f = func(1.0);
    int a = func(2);
}

答案 2 :(得分:1)

您可以使用整数来执行此操作:

template <typename T, bool isIntegral = std::is_integral<T>::value>
struct number_validator
{
   typedef WhatEverType type;
};

template <typename T>
struct number_validator<T, true>
{
    typedef WhatEverTypeInt type;
};

如果它是一个整数,将选择第二个特化,但如果它是一个浮点或其他类型,我不知道该怎么办。

相关问题