Jonathan Sharman Jonathan Sharman - 1 year ago 85
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

of non-
references (call it
). 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
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
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 Source

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;


template <typename T>
constexpr std::add_const_t<T>& as_const(T& t) noexcept{ return t; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download