c++ - 模板函数 C++ 类型的非常量引用的无效初始化

标签 c++ function-templates

在我的 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/

相关文章:

c++ - 函数模板链接错误

c++ - 模板构造函数重载问题

c++ - 如何使用折叠表达式创建 N 个浮点值的数组?

c++ - 将头文件包含到头文件中而不将其内容暴露给包含程序

c++ - 在 c++ std 库中,分配给索引 -1 处的映射元素

链表中的 C++ 内存泄漏 (Valgrind)

c++ - 使用函数指针的代码无法编译

c++ - 延迟函数模板实例化

c++ - 编译器内存优化 - 重用现有 block

c++ - 字符 vector 的奇怪输出