在我的 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
在我的主要 cpp 中
#include <FTemplate.h>
#include <Calculate.h>
int main()
{
Calculate cal;
Calculate cal1(42, 22);
Calculate cal2(95, 48);
cal difference = minus(cal1,cal2);
}
我正在尝试函数模板只是为了做一个简单的计算,但我遇到了这个错误:invalid initialization of non-const reference of type 'Calculate &' from an rvalue of type 'Calculate'
我在这里做错了什么?
最佳答案
您正在返回对由 return type1 - type2 ;
在
T& minus(const T& type1, const T& type2)
~~~
让它只是 T minus(const T& type1, const T& type2)
以按值返回。
type1 - type2
导致无法绑定(bind)到非 const 左值引用的右值。
关于c++ - 模板函数 C++ 类型的非常量引用的无效初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40626840/