数字类型的类模板

时间:2013-01-12 14:28:45

标签: c++ templates

如何编写仅接受数字类型(intdoublefloat等)作为模板的类模板?

2 个答案:

答案 0 :(得分:38)

您可以使用std::is_arithmetic类型特征。如果您只想启用具有此类型的类的实例化,请将其与std::enable_if结合使用:

#include <type_traits>

template<
    typename T, //real type
    typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
> struct S{};

int main() {
   S<int> s; //compiles
   S<char*> s; //doesn't compile
}

对于enable_if版本更易于使用且免费添加disable_if的版本,我强烈建议您阅读this wonderful article(或cached version)。

P.S。在C ++中,上述技术的名称称为“替换失败不是错误”(大多数使用首字母缩略词SFINAE)。您可以在wikipediacppreference.com上阅读有关此C ++技术的更多信息。

答案 1 :(得分:10)

我发现从template<typename T, typename = ...>方法收到的错误消息非常神秘(VS 2015),但发现具有相同类型特征的static_assert也有效,并允许我指定错误消息:

#include <type_traits>

template <typename NumericType>
struct S
{
    static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");
};

template <typename NumericType>
NumericType add_one(NumericType n)
{
    static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");
    return n + 1;
}

int main()
{
    S<int> i;
    S<char*> s; //doesn't compile

    add_one(1.f);
    add_one("hi there"); //doesn't compile
}
相关问题