C ++将模板类型限制为数字 [英] C++ Limit template type to numbers

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

问题描述

这是什么意思,我有一个用c ++编写的函数,要将资金存入帐户。该函数应该能够接受浮点数,双精度数,整数等,因为这些都是输入的有效形式,因为我所需要的只是一个要存入的数字。

What I mean is this, I have a function in c++ where I want to deposit money into an account. This function should be able to accept floats, doubles, integers, etc. as these are all valid forms of an input, as all I need is a number to deposit.

因此,我声明:

template <typename type>
void Deposit(type t) {...}

现在我唯一的问题就是这样:理论上,此类的用户可能会将char或string传递给此函数,并且这样做会产生意想不到的后果。我将如何限制类型为整数,浮点数,双精度数和短裤?是否可以将其限制在函数定义之内,以便其他人在使用此函数编程时遇到编译器/链接器错误,而不必使用 try {...} catch(...){。 ..}

Now the only issue I have is this: theoretically, a user of this class down the road could pass a char or string to this function and have unintended consequences of doing so. How would I go about restricting type to integers, floats, doubles and shorts? Is it possible to restrict this within the function definition so that others, when programming with this function get a compiler/linker error rather than having to use try{...} catch(...){...}?

推荐答案

您需要的内容 std :: is_arithmetic 将模板类型限制为算术类型(整数或浮点数)。您可以像这样使用它

What you need std::is_arithmetic to constrain the template type to a arithmetic types (integral or floating point). You can use it like

template <typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void Deposit(T t) {...}

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

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