Boost logo

Boost :

From: rwgk (rwgk_at_[hidden])
Date: 2002-03-14 22:21:45


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


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