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右值引用重载被删除,以禁止rvalue参数

[编辑] 可行实现

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 限定符
(类模板) [编辑]