#include <iostream>
using namespace std;
template <class U>
U add (U a, U b)
{
U c = 0 ;
c = a + b;
return c;
}
int main()
{
int first = 2;
int second = 2;
U result = 0;
result = add(first, second);
cout << result << endl;
return 0;
}
I want to declare the data type of result variable using the template data type so that my addition program is generic but the compiler is giving me this error "result was not declared in this scope."
What you are trying to do is not possible. You can only use U within your add function.
However, you can do this instead
auto result = add(first, second);
Or
decltype(auto) result = add(first, second);
In your case both will do the same. However, they are quite different. To make it short, decltype(auto)
will always get you the exact type returned by add
, while auto
may not.
Quick example:
const int& test()
{
static int c = 0;
return c;
}
// result type: int
auto result = test();
// result type: const int&
decltype(auto) result = test();
If you want to know more about auto, Scott Meyers explains it perfectly: