Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Limit template type to numbers

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.

Thus, I declared:

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

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(...){...}?

like image 241
Ryan Seipp Avatar asked Jun 30 '17 13:06

Ryan Seipp


2 Answers

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) {...}
like image 52
NathanOliver Avatar answered Oct 19 '22 14:10

NathanOliver


I am afraid you are getting wrong approach, you should create a class that properly work with money (including necessary operations for your domain - adding, subtracting etc), test it, add methods to print it and/or convert to string, and make your function accept only that type:

class Money {
    ...
};

void Deposit( Money amount );

So by adding constructors you can control which types can be accepted:

class Money {
public:
     explicit Money( double v );
     explicit Money( int64_t cents );
     Money( int64_t cents );
...
};

this way you can control what conversions can be done, and it would be done not only for this particular function but whole class. Otherwise you will need to re-implement the same logic in many functions (I doubt your system only would need functionality to deposit).

like image 41
Slava Avatar answered Oct 19 '22 14:10

Slava