pe********@gmail.com wrote:
In my case, I'd to open several output files at one time, but the
number of output files are determined at run-time, not compile-time.
So I tried to open file with std::ofstream when I need, and push the
std::ofstream object to a vector std::vector<std::ofstream>.
But I faced one problem that, the std::ofstream doesn't support a
asignment operator, so vector.push_back (ostream) cause an compile-time
error.
Does there are other ways that I can manange multiple files at
run-time?
There is a standard trick to use a reference counted smart pointer to turn
unique objects into container suitable things. Maybe you can start from the
following proof of concept:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
template <typename StreamType>
struct stream_handle {
typedef StreamType stream_type;
private:
typedef boost::shared_ptr< stream_type > stream_ptr;
stream_ptr my_ptr;
public:
stream_handle ( void )
: my_ptr ( new stream_type () )
{}
stream_handle ( stream_handle const & other )
: my_ptr ( other.my_ptr )
{}
~stream_handle ( void ) {}
stream_handle& operator= ( stream_handle const & other ) {
this->my_ptr = other.my_ptr;
return ( *this );
}
template < typename A >
stream_handle ( A const & a )
: my_ptr ( new stream_type ( a ) )
{}
template < typename A, typename B >
stream_handle ( A const & a, B const & b )
: my_ptr ( new stream_type ( a, b ) )
{}
template < typename A >
stream_handle & operator<< ( A const & a ) {
(*my_ptr) << a;
return ( *this );
}
template < typename A >
stream_handle & operator>> ( A & a ) {
(*my_ptr) >> a;
return ( *this );
}
}; // stream_handle<>
int main ( void ) {
typedef stream_handle< std::ofstream > o_handle;
std::vector< o_handle > handle_vect;
o_handle out ( "/dev/stdout" );
handle_vect.push_back( out );
handle_vect[0] << "hello world";
o_handle out2;
out2 = out;
out2 << '\n';
}
Best
Kai-Uwe Bux