std::as_const

< cpp‎ | utility
定义于头文件 <utility>
template <class T>
constexpr std::add_const_t<T>& as_const(T& t) noexcept;
(1) (C++17 起)
template <class T>
void as_const(const T&&) = delete;
(2) (C++17 起)
1) 将左值引用组成 t 的 const 类型
2) 删除 const 右值引用重载,以禁止右值参数

可能的实现

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

示例

#include <string>
#include <cassert>
#include <utility>
#include <type_traits>
 
int main()
{
    std::string mutableString = "Hello World!";
    auto&& constRef = std::as_const(mutableString);
 
//  mutableString.clear(); // OK
//  constRef.clear(); // 错误: 'constRef' 有 'const' 限定,但 'clear' 不标记为 const
 
    assert( &constRef == &mutableString );
    assert( &std::as_const( mutableString ) == &mutableString );
 
    using ExprType = std::remove_reference_t<decltype(std::as_const(mutableString))>;
 
    static_assert(std::is_same_v<std::remove_const_t<ExprType>, std::string>,
            "ExprType should be some kind of string." );
    static_assert(!std::is_same_v<ExprType, std::string>,
            "ExprType shouldn't be a mutable string." );
}

参阅

(C++11)
检查类型是否为 const 限定
(类模板)
(C++11)(C++11)(C++11)
添加 const 或/与 volatile 限定符到给定类型
(类模板)
(C++11)(C++11)(C++11)
从给定类型移除 const 或/与 volatile 限定符
(类模板)