Jonathan Sharman - 1 year ago 47

C++ Question

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

`std::vector`

`const`

`elements`

`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`

`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`

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;
}
```

or

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