Jonathan Sharman Jonathan Sharman - 2 months ago 14
C++ Question

Function for converting from T to const T in C++

I want to allow constant or non-constant iteration over a container class I wrote. My container stores elements in a

std::vector
of non-
const
references (call it
elements
). I'm using Boost's transform iterator to do this, e.g.:

auto begin() const
{
return boost::make_transform_iterator
( elements.begin()
, to_const<std::reference_wrapper<ElementType>>
);
}


Here I'm using a simple function template I wrote to convert an object of type
T
to
const T
:

template <typename T>
std::add_const<T>::type to_const(T value) { return value; }


I know it's trivial to write, but I just wanted to know if there's already an STL or Boost function template to do this, akin to
std::add_const
but as an actual function. (Alternatively, if anyone knows of a better way to lazily convert a vector of mutables to a vector of constants, that would be even better.)

Answer

In C++17, there is a <utility> template function to do that, std::as_const<T>, and BTW, this (below) isn't how to write it.

template <typename T>
std::add_const<T>::type to_const(T value) { return value; }

You are taking the argument by value which allows temporaries, and may require invocation of copy/move constructors; rather, use lvalue reference (aka, the object cannot be a temporary) as prototyped below:

template <typename T>
constexpr typename std::add_const<T>::type& as_const(T& t) noexcept{
    return t;
}

or

template <typename T>
constexpr std::add_const_t<T>& as_const(T& t) noexcept{ return t; }