I want to extract a data from a class; Currently, I use an auxiliary variable for it.
To work, it works ... but I was wondering if it could be done in another way, saving me the variable inside the function Envoltura::result( )
:
#include <iostream>
struct Base {
void ( *move )( Base *, void * );
inline Base( void ( *m )( Base *, void * ) ) : move( m ) { }
};
template< typename T > struct Derivada : public Base {
T value;
static inline void do_move( Base *b, void *p ) {
Derivada *d = static_cast< Derivada * >( b );
new ( p ) T( std::move( d->value ) );
}
inline Derivada( ) : Base( do_move ), value( 10 ) { }
};
template< typename T > struct Envoltura {
Base *base;
inline T result( ) {
union {
T tmp;
char dummy;
};
base->move( base, &tmp );
return tmp;
}
inline Envoltura( ) : base( new Derivada< T >( ) ) { }
};
int main( ) {
Envoltura< int > e;
int result = e.result( );
std::cout << "Resultado: " << result << std::endl;
return 0;
}
Compiled with g++ -std=c++11 -Wall -Wextra -pedantic
EDITO
It is necessary to maintain the class hierarchy exposed: a Base
, a template< > Derivada
daughter of the first, and a third template< > Envoltura
if inheritance of the previous ones. And no I can use virtual functions.