throws with gcc
}
catch(const std::exception &err)
{
cout << err.what() << "\n";
}
}
---------------------------------------------
Maybe some of the class names have alot of scope to be more
meaningful :-)
Here is an alternative idea (hopefully, I understood your aim):
#include <iostream>
struct oops {};
template < typename T >
class const_reference {
T const * ptr;
public:
const_reference ( T const & r )
: ptr ( &r )
{}
T const & get ( void ) {
return ( *ptr );
}
operator T const & ( void ) {
return ( *ptr );
}
};
template < typename T >
class reference {
T * ptr;
public:
reference ( T & r )
: ptr ( &r )
{}
T & get ( void ) {
return ( *ptr );
}
operator T & ( void ) {
return ( *ptr );
}
};
template < typename T >
class wrapper {
private:
T * the_ptr;
T const * the_c_ptr;
public:
wrapper ( T & ref )
: the_ptr ( &ref )
, the_c_ptr ()
{}
wrapper ( T const & cref )
: the_ptr ()
, the_c_ptr ( &cref )
{}
operator reference<T> ( void ) {
std::cout << "non-const\n";
if ( the_ptr ) {
return ( *the_ptr );
}
throw ( oops() );
}
operator const_reference<T> ( void ) {
std::cout << "const\n";
if ( the_ptr ) {
return ( *the_ptr );
}
return ( *the_c_ptr );
}
operator T ( void ) {
if ( the_ptr ) {
return ( *the_ptr );
}
return ( *the_c_ptr );
}
};
double const pi = 3.14159;
double e = 2.71828;
typedef wrapper< double > klass;
void foo_ref ( reference<double> ) {
std::cout << "reference\n";
}
void foo_cref ( const_reference<double> ) {
std::cout << "const reference\n";
}
void foo_val ( double ) {
std::cout << "value\n";
}
int main ( void ) {
klass rw ( e );
klass ro ( pi );
foo_val( rw );
foo_cref( rw );
foo_ref( rw );
foo_val( ro );
foo_cref( ro );
foo_ref( ro );
}
Best,
Kai-Uwe Bux
In my case the functions foo_ref, foo_cref, foo_val will be given (by
the client) and may ( and most probably will) be compiled without any
knowledge of the types reference and const_reference. So I would need
it to work with :
--------------------------
void foo_ref ( double & ) {
std::cout << "reference\n";
}
void foo_cref ( const double & ) {
std::cout << "const reference\n";
}
void foo_val ( double ) {
std::cout << "value\n";}
--------------------------
(In fact to be even more precise, in my real scenario they will be
class constructors.)
When I compile your code with above modifications I get the
compilation error:
-------------------------------------------------
main/main.cpp: In function 'int main()':
main/main.cpp:93:15: error: invalid initialization of reference of
type 'double&
' from expression of type 'klass'
main/main.cpp:72:6: error: in passing argument 1 of 'void
foo_ref(double&)'
main/main.cpp:96:15: error: invalid initialization of reference of
type 'double&
' from expression of type 'klass'
main/main.cpp:72:6: error: in passing argument 1 of 'void
foo_ref(double&)'
------------------------------------------------
Best
N
.....
It doesn't work as expected, specifically the last s.show() display 0.