Re: templates - method return value is multiple types
Christopher <cpisz@austin.rr.com> writes:
You guys kind of went off on a tangent on derived types. I was asking
about primitive types. I assume what I want isn't possible.
You can ?return? a value of either ?int? or ?double? type in a
certain figurative sense:
I call ?callee?, which will ?return? either an ?int? or a ?double?:
callee( this );
::std::cout << num->type() << '\n';
::std::cout << num->text() << '\n';
. This will print either
int
1
or
double
1
. The callee is looking like:
void callee( visitor * const v )
{ if( ::std::rand() )v->accept( 1 );
else v->accept( 1.0 ); }
, instead of an actual return, he uses ?v->accept?.
Now, the complete program:
#include <iostream>
#include <ostream>
#include <cstdlib>
#include <string>
#include <sstream>
struct visitor
{ virtual void accept( int const value )= 0;
virtual void accept( double const value )= 0; };
struct number
{ virtual ::std::string type()= 0;
virtual ::std::string text()= 0; };
struct integer : public number
{ int val;
integer( int const n ): val( n ){};
virtual ::std::string type(){ return "int"; };
virtual ::std::string text(){ std::stringstream out;
out << val; return out.str(); }};
struct floating : public number
{ double val;
floating( double const n ): val( n ){};
virtual ::std::string type(){ return "double"; };
virtual ::std::string text(){ std::stringstream out;
out << val; return out.str(); }};
void callee( visitor * const v )
{ if( ::std::rand() )v->accept( 1 );
else v->accept( 1.0 ); }
struct caller : public visitor
{ number * num;
void accept( int const value ){ this->num = new integer( value ); };
void accept( double const value ){ this->num = new floating( value ); };
void example()
{ callee( this );
::std::cout << num->type() << '\n';
::std::cout << num->text() << '\n'; }};
int main(){ caller().example(); }