c ++ boost :: any定义我自己的print, [英] c++ boost::any to define my own print ,
问题描述
我很努力找到如何使用 boost :: any
创建一个可以使用模板先打印任何类型的打印函数。
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 <typename T>
struct printer {
void print(ostream& os, const boost::any& a);
};
我需要定义第一个 print()
。想法很简单:给每个任何对象附加一个类
<$的实例。
i希望拥有真正的运算符< <
c $ c> printer< T> ,并且当 any
的值类型改变时更改此对象。
第一个技术问题是打印机对象依赖于T,而任何不是(并且不应该)类模板。
I need to define first print()
.
i wish to have the real operator <<
for any, The idea is simple: attach to each any object an instance of class
printer<T>
with the suitable T and change this object when the value type of the any
changes.
A first technical problem is that the printer object depends on T whereas any is not (and should not be) a class template.
请确实需要一个手是为今晚或明天我有明天的截止日期,但我希望今晚工作。
Please I really need a hand is for tonight or tomorrow I have a deadline for tomorrow but I wish to work on it tonight.
推荐答案
方法,请参阅超越C ++标准库:Boost简介 :
struct streamer {
virtual void print(ostream &o, const boost::any &a) const =0;
virtual streamer * clone() const = 0;
virtual ~streamer() {}
};
template <class T>
struct streamer_impl: streamer{
void print(ostream &o, const boost::any &a) const { o << *boost::any_cast<T>(a); }
streamer *clone() const { return new streamer_impl<T>(); }
};
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<class T> any_out(const T& value)
: streamer_(new streamer_impl<T>()), o_(value) {}
any_out(const any_out& a)
: streamer_(a.streamer_ ? a.streamer_->clone() : 0), o_(a.o_) {}
template <class T>
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;
}
};
,然后使用 any_out
code> boost :: any 。
and then you use any_out
instead of boost::any
.
这篇关于c ++ boost :: any定义我自己的print,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!