c++函数模板具体化出错


#include<iostream>
#include<string>
using namespace std;
class stu {
public:
    int age;
    string name;
    stu(int age, string name) {
        this->age = age;
        this->name = name;
    }
};
template<class T>
int equal(T a, T b) {
    return(a == b);
}
template<>int equal(stu& s1, stu& s2) {
    return (s1.age == s2.age && s1.name == s2.name);
}
void test1() {
    if (equal(10, 10))
        cout << "equal" << endl;
    else
        cout << "not equal" << endl;
}
void test2() {
    stu s1(10, "daming");
    stu s2(15, "daming");
    if (equal(s1, s2))
        cout << "equal" << endl;
    else
        cout << "not equal" << endl;
}
int main() {
    test2();
}

为什么会报错如下

错误 C2676 二进制“==”:“T”不定义该运算符或到预定义运算符可接收的类型的转换 c++learn D:\cjiajia\c++learn\c++learn\hellocp.cpp 15行

我把第十五行 参数也以引用传入就行了,但我不知道为什么要这样
或者18行不传引用也行,

  • 以下回答由chatgpt基于相关博客总结生成:

    问题的原因是,代码中定义的函数模板具体化使用了一个类型T,但是这个类型T没有定义相等运算符(==)或者无法将其转换为可以接受的类型。因此,在使用相等运算符(==)比较T类型的值时,编译器无法确定如何进行比较。

    解决这个问题的方法是: 1. 确保模板函数的具体化类型T已经定义了相等运算符(==),或者可以将其转换为可以接受的类型。 2. 如果T类型是自定义类型,需要按照C++的规范重载相等运算符(==)或者在类中定义它。 3. 如果T类型是指针类型,需要确保指针指向的对象或者指针类型本身都定义了相等运算符(==)。 4. 如果T类型是类模板,则需要确保类模板的具体化类型也满足上述要求。

    以下是一个修改后的示例代码,假设T为int类型:

    template<typename T>
    bool isEqual(T a, T b) {
        return a == b;
    }
    
    // 具体化函数模板
    template<>
    bool isEqual<int>(int a, int b) {
        return a == b;
    }
    
    int main() {
        int x = 10;
        int y = 20;
        if (isEqual(x, y)) {
            cout << "x and y are equal" << endl;
        } else {
            cout << "x and y are not equal" << endl;
        }
        return 0;
    }
    

    在这个示例代码中,我们使用template<>语法来定义了模板函数的具体化版本,具体化的类型为int。然后,在isEqual函数中使用了相等运算符(==)来比较两个int类型的值。

    这样,通过具体化函数模板,我们可以确保在使用int类型时能够进行相等比较。

结果

img


代码

#include<iostream>
#include<string>
using namespace std;

class stu {
public:
  int age;
  string name;

  stu(int age, string name) {
    this->age = age;
    this->name = name; 
  }
  
  // 添加 == 运算符重载
  bool operator==(const stu& rhs) const {
    return age == rhs.age && 
           name == rhs.name; 
  }
};

template<class T>
int equal(T a, T b) {
  return (a == b);
}

template<>
int equal(stu& s1, stu& s2) {
  return (s1.age == s2.age && s1.name == s2.name); 
}

void test1() {
  if (equal(10, 10))
    cout << "equal" << endl;
  else
    cout << "not equal" << endl; 
}

void test2() {
  stu s1(10, "daming");
  stu s2(15, "daming");
  
  if (equal(s1, s2)) 
    cout << "equal" << endl;
  else
    cout << "not equal" << endl;
}

int main() {
  test2();

  return 0;
}