Boost logo

Boost :

From: David Abrahams (david.abrahams_at_[hidden])
Date: 2002-03-14 22:47:06


This is a familiar issue. I have two proposals for you:

1. specialize for T const and cast away const-ness in the general
template:

template <class T>
struct ref : ref<T const>
{
    T* begin() { const_cast<T*>(this->ref<T const>::begin()); }
};

template <class T>
struct ref<T const>
{
    ...
};

2. Check out how const/non-const iterator interactions are handled
(differently) in the iterator adaptors lib. You can read about it in the
paper at www.boost.org/libs/utility/iterator_adaptors.pdf

-Dave

----- Original Message -----
From: "rwgk" <rwgk_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Thursday, March 14, 2002 10:21 PM
Subject: [boost] transitive_const?

> Does C++ provide some kind of "transitive_const" mechanism?
> Here is what I am after:
>
> template <typename T>
> struct ref {
> transitive_const T* ptr;
> ref(transitive_const T* p) : ptr(p) {}
> const T* begin() const { return ptr; }
> T* begin() { return ptr; }
> };
>
> Explanation:
>
> if ref<T> is constructed with a T*, both overloads for begin() will
> work. if ref<T> is constructed with a const T*, only the const
> version of begin() will work.
>
> In other words, if ref<T> is constructed with a const T* it will
> be identical to a const ref<T> and can only be used as such.
>
> Thought 1:
>
> Using ref<const T> is a bit problematic:
>
> template <typename T>
> void bar(const ref<T>& a1, const ref<T>& a2);
>
> This will not work if a1 is ref<const T> and a2 is ref<T> or
> vice versa.
>
> Right now my code looks like this:
>
> // separate type for const T*
> template <typename T>
> struct const_ref {
> const T* ptr;
> ref(const T* p) : ptr(p) {}
> const T* begin() const { return ptr; }
> };
>
> // separate type for T*
> template <typename T>
> struct ref {
> T* ptr;
> ref(T* p) : ptr(p) {}
> T* begin() { return ptr; }
> const T* begin() const { return ptr; }
> };
>
> The split into two separate types makes the following necessary:
>
> // generic function for const T*
> template <typename T>
> void
> foo(const_ref<T>& r);
>
> // hook for T*
> template <typename T>
> void
> foo(ref<T>& r) {
> foo(const_ref(r.begin()));
> }
>
> Thought 2:
>
> struct ref<T> : const_ref<T> { ... };
>
> This does not seem right because ref<T> will have two ptr.
>
> Thanks in advance for any enlightenment.
> Ralf
>
>
>
> Info: http://www.boost.org Send unsubscribe requests to:
<mailto:boost-unsubscribe_at_[hidden]>
>
> Your use of Yahoo! Groups is subject to
http://docs.yahoo.com/info/terms/
>
>
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk