0

in my FTemplate.h,

#ifndef FTemplate_h
#define FTemplate_h_h

template<typename T>
T& minus(const T& type1, const T& type2)
{
    return type1 - type2; // error here
}


#endif

in my main cpp

#include <FTemplate.h>
#include <Calculate.h>  
int main()
{
   Calculate cal;   
   Calculate cal1(42, 22);
   Calculate cal2(95, 48);
   cal difference = minus(cal1,cal2);

}

I am trying out function templates just to do a simple calculation but i met with this error : invalid initialization of non-const reference of type ‘Calculate &’ from an rvalue of type ‘Calculate ’ What have i done wrong here?

what
  • 373
  • 2
  • 10
  • 20
  • 1
    To understand the error, think of `return type1 - type2;` as something like this: `T& __function_result = type1 - type2; goto__end` (I'm not saying this is how C++ is implemented - just using it to illustrate what the error is telling you). When you call `minus` from `main`, then it looks like this `Calculate& __function_result = type1 - type2;` Now you should be able to see where there is an "initialization of non-const reference of type ‘Calculate &’" `__function_result` "from an rvalue of type ‘Calculate’" `type1 - type2`, This initialization is invalid as explained in the answers. – Allison Lock Nov 16 '16 at 09:51

2 Answers2

1

You're returning a reference to a temporary object created by return type1 - type2 ; in

T& minus(const T& type1, const T& type2)
~~~

Make it just T minus(const T& type1, const T& type2) for return by value.

type1 - type2 results in rvalue which cannot bind to non const lvalue references.

P0W
  • 46,614
  • 9
  • 72
  • 119
0

You are returning the result type1-type2 by reference. Which means you are taking a reference to a temporary object (technically Calculate&&) that will go out of scope. Try returning by value, i.e T& to T.

themagicalyang
  • 2,493
  • 14
  • 21