std::as_const

来自cppreference.com
< 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!";
    const std::string& constView = std::as_const(mutableString);
 
    assert( &constView == &mutableString );
    assert( &std::as_const( mutableString ) == &mutableString );
 
    using WhatTypeIsIt = std::remove_reference_t<decltype(std::as_const(mutableString))>;
 
    static_assert(std::is_same<std::remove_const_t<WhatTypeIsIt>, std::string>::value,
            "WhatTypeIsIt should be some kind of string." );
    static_assert(!std::is_same< WhatTypeIsIt, std::string >::value,
            "WhatTypeIsIt shouldn't be a mutable string." );
}


参阅

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