Как я могу изменить эту функцию, чтобы, если параметры функции были конкретными структурами, она возвращала структуру с большим целым числом? - PullRequest
0 голосов
/ 13 октября 2019

Мне нужно изменить эту максимальную функцию так, чтобы, если она имеет дело с struct Student, она возвращала максимальную оценку. Вот код:

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
typedef struct Student {
    char* name;
    int grade;
}Student;
template<typename  T>
T Max(T var1, T var2) {
    if (sizeof(T) == sizeof(Student))
        return(var1.grade > var2.grade) ? var1 : var2;
    return (var1 > var2) ? var1 : var2;
}
int main() {

    int i = 39;
    int j = 20;
    cout << "Max(i,j)=" << Max(i, j)<<endl;
    double f1 = 13.5;
    double f2 = 20.7;
    cout << "Max(f1,f2)=" << Max(f1, f2) << endl;
    string s1 = "Hello";
    string s2 = "World";
    cout << "Max(s1,s2)="<<Max(s1,s2) << endl;
    Student first_student;
    Student second_student;
    first_student.name = new char[30];
    second_student.name = new char[30];
    strcpy(first_student.name, "Popescu David");
    strcpy(second_student.name,"Gigel Petrovici");
    first_student.grade = 7;
    second_student.grade = 6;
    cout << "Max(student1,student2)=" << Max(first_student, second_student).grade << endl;
    return 0;
}

Но я получаю эти ошибки:

1>------ Build started: Project: OOP, Configuration: Debug Win32 ------
1>LastTODO.cpp
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(11): error C2228: left of '.grade' must have class/struct/union
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(11): note: type is 'T'
1>        with
1>        [
1>            T=int
1>        ]
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(22): note: see reference to function template instantiation 'T Max<int>(T,T)' being compiled
1>        with
1>        [
1>            T=int
1>        ]
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(11): error C2039: 'grade': is not a member of 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1>d:\visual studio\vc\tools\msvc\14.16.27023\include\xstring(4373): note: see declaration of 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(28): note: see reference to function template instantiation 'T Max<std::string>(T,T)' being compiled
1>        with
1>        [
1>            T=std::string
1>        ]
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(12): error C2676: binary '>': 'T' does not define this operator or a conversion to a type acceptable to the predefined operator
1>        with
1>        [
1>            T=Student
1>        ]
1>c:\users\dragos\source\repos\oop\oop\lasttodo.cpp(38): note: see reference to function template instantiation 'T Max<Student>(T,T)' being compiled
1>        with
1>        [
1>            T=Student
1>        ]
1>Done building project "OOP.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

1 Ответ

1 голос
/ 13 октября 2019

Начиная с C ++ 17, вы можете использовать if constexpr для запроса следующей строки

    return(var1.grade > var2.grade) ? var1 : var2;

скомпилируется, только если T равно Student:

template<typename  T>
T Max(T var1, T var2) {
    if constexpr ( std::is_same_v<T, Student> )
        return(var1.grade > var2.grade) ? var1 : var2;
    else
        return (var1 > var2) ? var1 : var2;
}

Демо


Другая возможность состоит в том, чтобы определить первичную версию Max как:

template<typename  T>
T Max(T var1, T var2) {
    return (var1 > var2) ? var1 : var2;
}

и предоставить специализацию для Student struct:

template<>
Student Max<Student>(Student var1, Student var2) {
    return(var1.grade > var2.grade) ? var1 : var2;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...