Hello Group,
I want to use this peace of code as
a core functionality for a polymorphic iterator.
Since i don't want to use plain new to create a
polymorphic iterator, i thought about this "workaround".
The actual storage is allocated on the stack
then inplace new constructs the object...
please tell me if the TEmbed<> is legal/valid/portable/c++?
and/or if there are other ways to do this...
By "portable" i mean: does this work on Win32(MSVC)
and Linux (GCC). I compiled it with MSVC7.1
and it worked.
template
<
typename Value,
size_t ValueSize = sizeof( Value )
class TEmbed
{
public:
typedef Value& reference;
typedef Value* pointer;
~TEmbed()
{
std::_Destroy( this->operator->() );
}
explicit TEmbed( const Value& value )
{
ASSERT( sizeof( value ) <= ValueSize );
std::_Construct( this->operator->(), value );
}
pointer operator->()
{
return reinterpret_cast< Value* >( bytes_ );
}
reference operator*()
{
return *reinterpret_cast< Value* >( bytes_ );
}
private:
char bytes_[ ValueSize ];
TEmbed();
};
// ----
struct Foo
{
Foo( int i = 0 ) : t_( i ) { }
int i_;
};
void bar()
{
typedef std::vector< Foo*> VecFooPtr;
typedef VecIFooPtr::iterator VecFooPtrIter;
typedef TEmbed< VecIFooPtrIter > EmbeddedIter;
Foo f0( 0 );
Foo f1( 1 );
Foo f2( 2 );
VecIFooPtr vec;
vec.push_back( &f0 );
vec.push_back( &f1 );
vec.push_back( &f2 );
EmbeddedIter embIterBeg( vec.begin() );
EmbeddedIter embIterEnd( vec.end() );
}
many thanks
DonBot