Am struggling a lot to find how to do to use boost::any
to create a print function that can print any type using template first.
template
There is quite easy way to do this, described in "Beyond the C++ Standard Library: An Introduction to Boost":
struct streamer {
virtual void print(ostream &o, const boost::any &a) const =0;
virtual streamer * clone() const = 0;
virtual ~streamer() {}
};
template
struct streamer_impl: streamer{
void print(ostream &o, const boost::any &a) const { o << *boost::any_cast(a); }
streamer *clone() const { return new streamer_impl(); }
};
class any_out {
streamer *streamer_;
boost::any o_;
void swap(any_out & r){
std::swap(streamer_, r.streamer_);
std::swap(o_, r.o_);
}
public:
any_out(): streamer_(0) {}
template any_out(const T& value)
: streamer_(new streamer_impl()), o_(value) {}
any_out(const any_out& a)
: streamer_(a.streamer_ ? a.streamer_->clone() : 0), o_(a.o_) {}
template
any_out & operator=(const T& r) {
any_out(r).swap(*this);
return *this;
}
~any_out() { delete streamer_; }
friend std::ostream &operator<<(std::ostream& o, const any_out & a) {
if(a.streamer_)
a.streamer_->print(o, a);
return o;
}
};
and then you use any_out
instead of boost::any
.