和
STL
的
utility
一樣,
boost/utility
里包含了一些實用的小工具。
首先是
? Base-from-Member
:
有時你可能需要依賴成員變量來初始化基類,像這樣:
class
?fdoutbuf
????:?
public
?std::streambuf
{
public
:
????
explicit
?fdoutbuf(?
int
?fd?);
????
//
};
class
?fdostream
????:?
public
?std::ostream
{
protected
:
????fdoutbuf?buf;
public
:
????
explicit
?fdostream(?
int
?fd?)
????????:?buf(?fd?),?std::ostream(?
&
buf?)
????????{}
????
//
};
但是,這里
fdostream
的構造函數的初始化是錯誤的,因為
c++
語法要求基類的初始化要先于成員變量的初始化。
Base-from-Member
提供的解決之道如下:
class
?fdoutbuf
????:?
public
?std::streambuf
{
public
:
????
explicit
?fdoutbuf(?
int
?fd?);
????
//
};
class
?fdostream
????:?
private
?boost::base_from_member
<
fdoutbuf
>
????,?
public
?std::ostream
{
????
//
?Helper?typedef's
????typedef?boost::base_from_member
<
fdoutbuf
>
??pbase_type;
????typedef?std::ostream????????????????????????base_type;
public
:
????
explicit
?fdostream(?
int
?fd?)
????????:?pbase_type(?fd?),?base_type(?
&
member?)
????????{}
????
//
};
模板類
template < typename MemberType, int UniqueID = 0 >
??????? class boost::base_from_member;
是一個外覆類(姑且這么叫了
^_^
)。
如上,私有繼承
base_from_member
,原先的成員變量將做為
base_from_member
的成員變量
member
先于基類
base_type
初始化,這樣所需的依賴關系可以滿足。事實上比這更好的是,
base_from_member
的構造函數是模板函數,它可以有
0
至
10
個參數,參數類型可以各不相同。
posted on 2006-08-11 23:59
小山日志 閱讀(520)
評論(0) 編輯 收藏 引用 所屬分類:
stl/boost/loki/generically