Boost logo

Boost :

Subject: [boost] [type traits] add a set of templates to propagate const etc from one type to another?
From: Vasilis Vasaitis (v.vasaitis_at_[hidden])
Date: 2010-03-02 10:27:17


  Hello,

  I've been looking at the Type Traits library recently, and it looks
wonderful overall. However, it's lacking a use case that I end up
needing quite often, so I thought I'd suggest it in case the authors
and/or other users of the library find it useful. Allow me to explain.

  So Type Traits has the add_const / remove_const / is_const triplet
(and similar for a few other type properties). add_const is great when
you always know that you want to add the const, but sometimes you only
want to do it conditionally to another type being const. So recently
I've ended up using something like this from quite a few places in my
code:

template<class Source, class Target>
struct propagate_const {
    typedef Target type;
};

template<class Source, class Target>
struct propagate_const<const Source, Target> {
    typedef const Target type;
};

  That is, propagate_const<Source, Target> will only add const to
Target if Source is const too.

  What are the use cases for this? Well, for example recently I was
writing an iterator class, and I wanted to avoid duplicating the code
for the const_iterator case. Not a big deal, as it turned out, as I
could just pass a const type as the template argument and have it
behave as the const iterator. The only problem was that I was doing
some pointer arithmetic with reinterpret_casts from T* to char* and
back (where T is the template argument), so the compiler would
complain if T was const. So instead of char I defined this:

typedef typename propagate_const<T, char>::type char_type;

  Of course I could also have done this with a combination of is_const
and add_const, but this would probably require more code than the
propagate_const definition above.

  So what do people think? Would it be a useful addition alongside
add_* and remove_*?

Thanks,
Vasilis

P.S. Please CC me in your replies, as I've set the mailing lists to
not send me emails (similar to not being subscribed).

-- 
Vasilis Vasaitis
"A man is well or woe as he thinks himself so."

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