In C++ How do I template the return value to be unique from the parameter value? My code looks as follows - now if data type of number is int going in I want it as a double going out.
template <class T>
T divide(T number)
{
return number/10;
}
in main I have this
divide(5);
divide(2.5);
In the case of 2.5 the value going in and out will be type double so there isn't a problem but in the case of 5 it goes in as an int but I need it to not be truncated and returned as type double.
template <class T, Class T1>
T1 divide(T number)
{
return number/10;
}
That doesn't work because its looking for two parameters in the functions.
T1 template <class T>
T1 divide(T number)
{
return number/10;
}
this gives me no declaration of storage class or type specifier - when I add the word class to that line before T1 I get the error message: function returns incomplete type.
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.
There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.
"A function template is a template that is used to generate functions. A template function is a function that is produced by a template. For example, swap(T&, T&) is a function tem-plate, but the call swap(m, n) generates the actual template function that is invoked by the call."
The most generic method is to have a helper template
template <typename T>
struct calc_return {
using type = T;
};
template <class T>
typename calc_return<T>::type divide(T number)
{
return number/10;
}
Now if there are exceptions to the rule, you specialize calc_return
using whatever logic you'd like:
// Prior to the declaration of divide()
template <>
struct calc_return<int> {
using type = double;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With