|
Boost : |
From: Schoenborn, Oliver (Oliver.Schoenborn_at_[hidden])
Date: 2002-10-03 16:12:44
> "Eric Woodruff" <Eric.Woodruff_at_[hidden]> wrote in message
> news:ani8r4$6h1$1_at_main.gmane.org...
> > No, that wont work. That would still require it's base to
> be copied--the
> > same copy that occurs already.
> > [...]
>
> Hmm...I just tried this code, and Comeau warns that the
> conversion operator will not be called for implicit or
> explicit conversions. Any idea why?
I would also like to find out. In any case, I have used this technique to
get around it:
template <typename T>
class smart_ptr;
template <typename T>
class smart_ptr<const T> { /*...stuff...*/ };
template <typename T>
class smart_ptr : smart_ptr<const T> {
public:
const smart_ptr<const T>& ofConst() const
{
return *this;
}
};
This means that a user can't just give a smart_ptr<T> to a function that
expects a smart_ptr<const T>, but must call smart_ptr<T>::ofConst():
void f(const smart_ptr<const T>&) {...}
int main() {
smart_ptr<T> foo;
f(foo.ofConst());
}
This may appear verbose or clunky at first, but I like the fact that:
- it makes obvious to the user that they are passing an object different
from what is expected
- it prevents the user from passing a non-const smart_ptr<const T> (would be
dangerous if allowed)
Oliver
> template <typename T>
> class const_shared_ptr
> {
> public:
> typedef T const element_type;
> };
>
> template <typename T>
> class shared_ptr : const_shared_ptr<T>
> {
> public:
> operator const_shared_ptr<T> const&() const
> {
> return static_cast<const_shared_ptr<T> const&>(*this);
> }
> };
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk