Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2004-04-12 11:22:54

Brian McNamara <lorgon_at_[hidden]> writes:

> On Tue, Apr 13, 2004 at 12:26:35AM +1000, Thorsten Ottosen wrote:
>> I think I have found a safe way to bind a temporary to a const reference
>> and cast away the constness.
>> This means that a temporary can be passed (relatively) safely to an
>> algorithm with a prototype like
> ...
>> Comments are welcome.
> Cute use of compile-time ambiguity to ensure that you don't try to
> mutate const objects.
> Offhand it seems like it is "safe", in the sense of
> lifetime-of-the-temporary issues.

Seems like this would be more useful.
template <class T>
T& mutate_rvalue(T& x, int) { return x; }

template <class T>
T& mutate_rvalue(T const& x, ...) { return const_cast<T&>(x); }

// test code
#include <string>

typedef int yes;
typedef char* no;

template <class T>
yes is_mutable(T&);
template <class T>
no is_mutable(T const&);

std::string x;
std::string const y;

yes a = is_mutable(mutate_rvalue(x,0));
no b = is_mutable(mutate_rvalue(y,0));
yes c = is_mutable(mutate_rvalue(x+y,0));

> What's an example use-case? I don't recall ever needing/wanting
> this.

Howard Hinnant brought up some cases, during LWG discussion of
iterator adaptors, where you might want to mutate an object if you had
permission to, for example in some linear algebra you might want to do
part of the algorithm in-place. If it was generic code you'd want to
take the same liberties with rvalues as with mutable lvalues.

Dave Abrahams
Boost Consulting

Boost list run by bdawes at, gregod at, cpdaniel at, john at