c++ - 在 C++ 中从 T 转换为 const T 的函数

标签 c++ boost vector stl constants

我想允许对我编写的容器类进行常量或非常量迭代。我的容器将元素存储在非 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/

相关文章:

当字符串和位集大小正确时,C++ ValueError bitset::_M_copy_from_ptr

c++ - Boost::Positional Options 无法使所有参数位置化

c++ - Target Boost::<library> 已有导入位置 + 链接错误

c++ - 访问类的元素

c++ - 在双菱形中到达远处基类的字段或方法的方法是什么?

c++ - 如何编译 C++ 代码并将其与已编译的 C 代码链接?

c++ - 如何将 printf xterm 代码转换为 ostringstream?

C++优化函数调用批处理模式

c++ - 使用 CUDA 在集合中查找最少的数字

c++ - 如何在二维 vector 中打印所有 8 个邻居(段错误)