Search code examples
c++c++11constantstemplate-argument-deduction

For a type Class::Type, can I derive const Class::Type from a const Class?


I am implementing a container like:

template<typename T>
class Container
{
public:
    using value_type = T;
    ...
};

Is there a good way to derive a const value_type from const Container?

Background:

I have implemented iterator types via a nested template class:

template<typename Container, typename Value>
class iterator_base
{
public:
    ...
    Value& operator*() const;

private:
    Container* c;
};

using iterator = iterator_base<Container, value_type>;
using const_iterator = iterator_base<const Container, const value_type>;

which works okay, but the second template argument to iterator_base feels redundant.


Solution

  • The obvious way would be to remove the second parameter, and rely on the const-ness of the first in determining if const should be added. The standard library has some useful meta-functions for this:

    #include <type_traits>
    
    template<typename Container>
    class iterator_base
    {
      using Value = typename std::conditional<std::is_const<Container>::value,
                      typename std::add_const<typename Container::value_type>::type,
                      typename Container::value_type>::type;
    public:
        ...
        Value& operator*() const;
    
    private:
        Container* c;
    };