For type Class :: Type, can I get const Class :: Type from class const?

I implement a container, for example:

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

Is there a good way to get const value_typeout const Container?

Background:

I implemented iterator types through 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 fine, but the second argument to the template iterator_baseseems redundant.

+6
source share
1 answer

The obvious way would be to remove the second parameter and rely on the constant of the first when deciding whether to add const. 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;
};
+7
source

All Articles