我想允许对我编写的容器类进行常量或非常量迭代。我的容器将元素存储在非 const
引用的 std::vector
中(称之为 elements
)。我正在使用 Boost 的 transform iterator这样做,例如:
auto begin() const
{
return boost::make_transform_iterator
( elements.begin()
, to_const<std::reference_wrapper<ElementType>>
);
}
在这里,我使用我编写的一个简单函数模板将 T
类型的对象转换为 const T
:
template <typename T>
std::add_const<T>::type to_const(T value) { return value; }
我知道编写起来很简单,但我只是想知道是否已经有一个 STL 或 Boost 函数模板来执行此操作,类似于 std::add_const
但作为一个实际函数。 (或者,如果有人知道有更好的方法将可变 vector 延迟转换为常量 vector ,那就更好了。)
最佳答案
在 C++17 中,有一个 <utility>
模板函数来做到这一点, std::as_const<T>
, 顺便说一句,这(下面)不是怎么写的。
template <typename T>
std::add_const<T>::type to_const(T value) { return value; }
您正在按值获取参数,这允许临时变量,并且可能需要调用复制/移动构造函数;相反,使用 lvalue
引用(又名,对象不能是临时的)如下原型(prototype):
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; }
关于c++ - 在 C++ 中从 T 转换为 const T 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543458/