MESSAGE
DATE | 2011-04-11 |
FROM | Ruben Safir
|
SUBJECT | Subject: [NYLXS - HANGOUT] C++ Workshop templated operator()<<]
|
as I understand things, the operator<<() needs to be external as to the class and then declared as a friend of the class. I'm not sure if I understand why that is the case.
I did this with a class called MESSAGE and had not trouble with the general implementation. However, when I tried to do this with a templated class that generally looks like, although this is not compiling
namespace stats{
template class Distribution { template friend std::ostream & operator<<(std::ostream &, const Distribution&); public: /* ==================== LIFECYCLE ======================================= */ Distribution (T descr, int occurances = 0); Distribution():freq(NULL),occurances(NULL){}; // Distribution ( const Distribution &other ); /* copy constructor */ // ~Distribution (); /* destructor */ /* ==================== ACCESSORS ======================================= */ T description(){ return freq;} int population() { return occurances; } /* ==================== MUTATORS ======================================= */ void increase_occ(){ ++occurances; std::cout << "description " << freq << " occurances " << occurances << std::endl; } void descrease_occ(){ --occurances; } /* ==================== OPERATORS ======================================= */ //Distribution& operator = ( const Distribution &other ); /* assignment operator */ int operator()(){ return freq; } bool operator==(Distribution &tmp){ if(this->freq == tmp.freq) return true; return false; }
bool operator<(Distribution &tmp){ if(freq < tmp.freq) return true; return false; }
protected: /* ==================== DATA MEMBERS ======================================= */ private: /* ==================== DATA MEMBERS ======================================= */ T freq; //description of how many times found in a List int occurances; //description of how many times a frequency was found in a list }; /* ----- end of class Distribution ----- */
template std::ostream & operator << ( std::ostream & os, const Distribution & obj ) { T desc = obj.description(); int pop = obj.population(); os << "The Identification of " << desc << " was seens " << pop ; return os; } /* ----- end of function operator << ----- */
Not this is not compiling because:
test_del.cpp|90| error: passing ?const stats::Distribution? as ?this? argument of ?T stats::Distribution::description() [with T = int]? discards qualifiers
which is on the call for the use of the << operator on the class. before I templated the operaotr<<(), I got a warning that I was using a non-templated function. I've done some research and this peoblem seems to have been common, but I don't know of any solutions, and I don't understand what the implementation issue is.
----- End forwarded message -----
|
|