C++ Explicit specialization question
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <typeinfo>
#include <cstring>
using namespace std;
struct student
{
int age;
};
template <typename T1, typename T2> auto comparex(const T1 a,const T2 b) -> decltype(a+b);
template <typename T1, typename T2> auto comparex(const T1 a,const T2 b) -> decltype(a+b)
{
return a > b ? a : b;
}
template <> student comparex(const student a, const student b);
template <> student comparex(const student a, const student b)
{
return (a.age > b.age) ? a : b;
}
int main()
{
student s1, s2;
s1.age = 20;
s2.age = 13;
cout << comparex<int, double>(2, 16.6) << "\n";
cout << comparex<student,student>(s1,s2).age << "\n"; // Error
return 0;
}
|
How to explicit specialize the student ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <typeinfo>
#include <cstring>
using namespace std;
struct student
{
int age;
};
template <typename T> int comparex(const T a,const T b);
template <typename T> int comparex(const T a,const T b)
{
return a > b ? a : b;
}
template <> student comparex(const student a, const student b);
template <> student comparex(const student a, const student b)
{
return (a.age > b.age) ? a : b;
}
int main()
{
student s1, s2;
s1.age = 20;
s2.age = 13;
cout << comparex(2, 16) << "\n";
//cout << comparex(s1,s2).age << "\n";
return 0;
}
|
Sample 2
How to specialize the "student"
don't, overload instead.
For your second example
1 2
|
template <typename T> T comparex(const T a,const T b);
template <> student comparex(const student a, const student b){
|
Also, `max' would be a better name
Topic archived. No new replies allowed.