Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 479
jamesdlin Avatar asked Aug 21 '17 12:08

jamesdlin


1 Answers

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;
};
like image 131
StoryTeller - Unslander Monica Avatar answered Sep 17 '22 22:09

StoryTeller - Unslander Monica