请考虑以下代码段: class Foo {public: Foo( int Value ); // other stuff};std::list boost::shared_ptr Foo ListOfFoo = list_of( 1 )( 2 )( 3 )( 4 )( 5 ); 这不是开箱即用的.使这个工作最简单的方法是什么,或者是否有
class Foo {
public:
Foo( int Value );
// other stuff
};
std::list< boost::shared_ptr< Foo > > ListOfFoo = list_of( 1 )( 2 )( 3 )( 4 )( 5 );
这不是开箱即用的.使这个工作最简单的方法是什么,或者是否有任何方法为ListOfFoo赋值如此简单?
boost::assign::ptr_list_of允许您使用非常简单的语法构造
Boost pointer container.您可以通过私有继承扩展它,以便它可以创建shared_ptr的容器:
template< class T >
struct shared_ptr_list : boost::assign_detail::generic_ptr_list<T>
{
typedef boost::assign_detail::generic_ptr_list<T> Base;
template< class Seq >
operator Seq() const
{
Seq result;
for(typename Base::impl_type::iterator it = Base::values_.begin(), e = Base::values_.end(); it != e; ++it)
result.push_back(typename Seq::value_type(&*it));
Base::values_.release().release();
return result;
}
template< class U >
shared_ptr_list& operator()( const U& u )
{
return (shared_ptr_list&)boost::assign_detail
::generic_ptr_list<T>::operator()(u);
}
};
template< class T, class U >
shared_ptr_list<T> shared_ptr_list_of( const U& t )
{
return shared_ptr_list<T>()(t);
}
它看起来有点难看但是它使用起来非常方便:
int main()
{
using boost::shared_ptr;
std::deque<shared_ptr<Foo> > deq = shared_ptr_list_of<Foo>(1)(2)(3);
}
