数字类型的类模板 [英] Class template for numeric types

查看:46
本文介绍了数字类型的类模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写仅接受数字类型( int double float 等)作为模板?

How do I write a class template that accepts only numeric types (int, double, float, etc.) as template?

推荐答案

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

You can use the std::is_arithmetic type trait. If you want to only enable instantiation of a class with such a type, use it in conjunction with 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 ,我强烈建议阅读关于这件事的这篇精彩文章

For a version of enable_if that's easier to use, and a free addition of disable_if, I highly recommend reading this wonderful article on the matter.

ps在C ++中,上述技术的名称称为替换失败不是错误(大多数使用缩写词SFINAE)。您可以在维基百科 cppreference.com

p.s. In C++, the technique described above has a name called "Substitution Failure Is Not An Error" (most use the acronym SFINAE). You can read more about this C++ technique on wikipedia or cppreference.com.

这篇关于数字类型的类模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆