Disallow taking pointer/reference to const to a temporary object in C++ (no C++0X)
Posted
by
KRao
on Stack Overflow
See other posts from Stack Overflow
or by KRao
Published on 2010-11-09T12:36:00Z
Indexed on
2011/01/13
14:53 UTC
Read the original article
Hit count: 160
Hi, I am faced with the following issue. Consider the following class:
//Will be similar to bost::reference_wrapper
template<class T>
class Ref {
public:
explicit Ref(T& t) : m_ptr(&t) {}
private:
T* m_ptr;
};
and this function returning a double
double fun() {return 1.0;}
If we now have
double x = 1.0;
const double xc = 1.0;
Ref<double> ref1(x); //OK
Ref<const double> refc1(cx); //OK
good so far, however:
//Ref<double> ref2( fun() ); //Fails as I want it to
Ref<const double> refc2( fun() ); //Works but I would like it not to
Is there a way to modify Ref (the way you prefer) but not the function fun, so that the last line returns a compile-time error? Please notice you can modify the constructor signature (as long as I am able to initialise the Ref as intended). Thank you in advance for your help!
© Stack Overflow or respective owner