std::as_const - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::as_const

From cppreference.com
< cpp‎ | utility

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

Run this code

    #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." );
    }

### [edit] See also

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

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/utility/as_const&oldid=81985"