Reputation: 13
I'm trying to calculate the absolute value of two numeric values passed in by a user, but allowing the user to enter multiple data types (i.e. an integer and a double, or a char and a float). My initial thought is to use a function sort of like this:
template <class T1, class T2>
void findAbs(const T1& var1, const T2& var2)
{
cout<<"Enter two numbers: "<<endl;
cin>>var1>>var2;
cout<<abs(var1)<<" "<<abs(var2)<<endl;
}
If this is the correct way to do it though, I have no idea how I'd call it in the main function since it seems I'd have to declare the parameters as one data type or another. Any help would be much appreciated!
Upvotes: 1
Views: 3701
Reputation: 171117
First off, your example won't compile, because you're taking the parameters by const-reference, and then trying to read into them from the stream. You should take them by non-const reference instead.
With this fixed, you could simply use the function like this:
int main()
{
int i;
float f;
double d;
char c;
findAbs(i, f);
findAbs(c, d);
findAbs(d, i);
//etc.
}
Of course, the type of the arguments must be known in each call site. Templates are a purely compile-time construct. If you were hoping to somehow use the template to differentiate between the end-user typing c
, 42
or -3.14
, you can't, as that's run-time information.
Upvotes: 4
Reputation: 76240
I have no idea how I'd call it in the main function since it seems I'd have to declare the parameters as one data type or another.
No, template parameters can be deduced in this case. But the main problem is that operator>>
of std::cin
modifies the parameters, therefore you shouldn't declare them const
:
template <class T1, class T2>
void findAbs(T1& var1, T2& var2) {
std::cout << "Enter two numbers: " << std::endl;
std::cin >> var1 >> var2;
std::cout << std::abs(var1) << ' ' << std::abs(var2) << std::endl;
}
Then you should be able to call:
int x, y;
findAbs(x, y);
It might be wise to consider using a single template parameter for both of the arguments though.
Upvotes: 1
Reputation: 124632
Yes, but it depends on whether or not the types you pass in would lead to a piece of code which is valid. Expand the template in your head (or type it out, whatever). Does calling abs
on variables of type T1
and T2
make sense? Would it compile? How about the calls to cin
? If so, then yes, your code will work.
Upvotes: 0