简体   繁体   中英

template functions c++ invalid initialization of non-const reference of type

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?

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.

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, ie T& to T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM