c++ - How to pass strcut Datatype into template? -
i have 2 template classes inherits each other. , have struct date want pass function in 1 of classes error when compile:
no operator found takes right-hand operand of type 'date' (or there no acceptable conversion)
the error in line 95 specifically.
as can see in code, passing different data types test if function works. of them worked except struct date.
what doing wrong?
my code:
#include <iostream> #include <string> using namespace std; template <typename t> class b; //forward declare template <typename t> class { t valuea; public: a(){}; t getvaluea() { return valuea; } void setvaluea(t x) { valuea = x; } a(const &x) { valuea = x.valuea; } friend class b<t>; //a<int> friend of b<int> }; template <typename t> class b : a<t> { t valueb; public: using a<t>::setvaluea; using a<t>::getvaluea; b(){}; t getvalueb() { return valueb; } void setvalueb(t x) { valueb = x; } b(const b &x) { valueb = x.valueb; this->valuea = x.valuea; } }; struct date { int day; int month; int year; }; int main() { b<float> b; b.setvaluea(1.34); b.setvalueb(3.14); cout << "b.setvaluea(1.34): " << b.getvaluea() << endl << "b.setvalueb(3.14): " << b.getvalueb() << endl; b<int> a; a.setvaluea(1); a.setvalueb(3); cout << "a.setvaluea(1): " << a.getvaluea() << endl << "a.setvalueb(3): " << a.getvalueb() << endl; b<char> y; y.setvaluea('a'); y.setvalueb('c'); cout << "y.setvaluea('a'): " << y.getvaluea() << endl << "y.setvalueb('c'): " << y.getvalueb() << endl; b<string> u; u.setvaluea("good"); u.setvalueb("morning"); cout << "u.setvaluea(good): " << u.getvaluea() << endl << "u.setvalueb(morning): " << u.getvalueb() << endl; b<date> p; p.setvaluea({ 27, 10, 2014 }); p.setvalueb({ 2, 11, 2014 }); cout << "p.setvaluea({ 27, 10, 2014 }): " << p.getvaluea() << endl << "p.setvalueb({ 2, 11, 2014 }): " << p.getvalueb() << endl; system("pause"); return 0; }
you need provide operator<<
date class, otherwise doesn't know how output stream. try following:
struct date { int day; int month; int year; friend ostream& operator << (ostream& os, const date& date) { return os << "day: " << date.day << ", month: " << date.month << ", year: " << date.year << " "; } };
live example: http://ideone.com/ehio6q
Comments
Post a Comment