rsdev
rsdev

Reputation: 140

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

Upvotes: 8

Views: 8743

Answers (2)

Slava
Slava

Reputation: 44248

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).

Upvotes: 5

NathanOliver
NathanOliver

Reputation: 180500

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

Upvotes: 18

Related Questions