Sharad Kala wrote:
can't write - template <struct Mytype>, but template <class Mytype> is
perfectly legal.
[newbie]
hmmm ... I want to check if structs are compatible with classes for
templates.
So I wrote a small program and verified that is indeed the case :-)
Comments from you gurus appreciated.
#include <iostream>
/* struct */
/* this should be in a header file */
struct S {
int a;
int b;
S operator+(S);
};
/* this should be in a separate code file */
S S::operator+(S x) {
S temp;
temp.a = this->a + x.a;
temp.b = this->b + x.b;
return temp;
}
std::ostream & operator<<(std::ostream & in, const S & x) {
std::cout << "(" << x.a << ", " << x.b << ")";
return in;
}
/* end struct */
/* class */
/* this should be in a header file */
class C {
int a;
int b;
public:
C(int, int);
C operator+(C);
friend std::ostream & operator<<(std::ostream & in, const C & x);
};
/* this should be in a separate code file */
C::C(int x, int y) {
this->a = x;
this->b = y;
}
C C::operator+(C x) {
C temp(0, 0);
temp.a = this->a + x.a;
temp.b = this->b + x.b;
return temp;
}
std::ostream & operator<<(std::ostream & in, const C & x) {
std::cout << "(" << x.a << ", " << x.b << ")";
return in;
}
/* end class */
template<class CLASS_OR_STRUCT>
CLASS_OR_STRUCT test_sum(CLASS_OR_STRUCT x, CLASS_OR_STRUCT y) {
return x + y;
}
int main() {
int ix=6, iy=-5;
double dx=-3, dy=5;
S Sx={5, 0}, Sy={-2, 4};
C Cx(-3, 3), Cy(8, 3);
using std::cout;
using std::endl;
cout << test_sum(ix, iy) << endl;
cout << test_sum(dx, dy) << endl;
cout << test_sum(Sx, Sy) << endl;
cout << test_sum(Cx, Cy) << endl;
}
--
USENET would be a better place if everybody read:
http://www.expita.com/nomime.html http://www.netmeister.org/news/learn2quote2.html http://www.catb.org/~esr/faqs/smart-questions.html