Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ How do I template the return value to be unique from the parameter value?

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.

like image 987
YelizavetaYR Avatar asked Nov 12 '14 00:11

YelizavetaYR


People also ask

Can we pass Nontype parameters to templates?

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.

What is a template parameter?

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.

What is the difference between typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.

What is the difference between the function template and template function?

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


1 Answers

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;
};
like image 196
MSalters Avatar answered Oct 04 '22 06:10

MSalters