@ XSI
And when I get const, it takes me to another problem, I change the stringstream, so I must declare mutable? if so I have yet another problem on copy constructor and = which are not accessible, I try to encapsulate it in a auto_ptr, but it does not work better.
@ fellah
why friend, yes I know that the use of friend is not often a good idea, then it's just that I recall most of the syntax that allows to do without them
With the code below it works, but no more simple/clean
Code:
# include <vector>
# include <iostream>
# include <sstream>
# include <iterator>
using std::cout;
using std::stringstream;
using std::ostream;
using std::swap;
template <typename T> struct ValueInit;
template <> struct ValueInit<int> { static int Init() { return 0;}};
template <> struct ValueInit<std::string> { static std::string Init() { return "";}};
template <typename T>
struct MyClass
{
explicit MyClass (T m = ValueInit <T>::Init ()):
m_(m)
, ss_(std::auto_ptr <stringstream> (new stringstream ())){}
MyClass (const MyClass & m): m_ (m.m_) ss_ (m.ss_) {}
void Swap (MyClass & mwc)
{
std::swap (ss_, mwc.ss_);
std::swap (m_, mwc.m_);
}
MyClass & operator = (MyClass m)
{
Swap (m);
return * this;
}
void print (ostream & o) const
{
o <<get ();
}
std:: string get () const
{
* ss_ <<m_;
return ss_-> str ();
}
private:
mutable std:: auto_ptr <stringstream> ss_;
T m_;
};
template <class T>
std::ostream & operator <<(std::ostream & o, const MyClass <T> & m)
{
m.print (o);
return o;
}
void main ()
{
typedef MyClass <int> MYI
MYI z (9);
std::vector <MYI> Tab1;
Tab1.push_back (z);
std::copy (Tab1.begin (), Tab1.end (), std::ostream_iterator <MYI> (cout));
}
Bookmarks