Namespaces
Variants
Views
Actions

std::as_const

From cppreference.com
< cpp‎ | utility
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
as_const
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)

Stacktrace
 
Defined in header <utility>
template <class T>
constexpr std::add_const_t<T>& as_const(T& t) noexcept;
(1) (since C++17)
template <class T>
void as_const(const T&&) = delete;
(2) (since C++17)
1) Forms lvalue reference to const type of t
2) const rvalue reference overload is deleted to disallow rvalue arguments

[edit] Possible implementation

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

[edit] Example

#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(); // error: 'constRef' is 'const' qualified,
                      //        but 'clear' is not marked 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." );
}

[edit] See also

(C++11)
checks if a type is const-qualified
(class template) [edit]
(C++11)(C++11)(C++11)
adds const or/and volatile specifiers to the given type
(class template) [edit]
removes const or/and volatile specifiers from the given type
(class template) [edit]