std::as_const – cppreference.com

std::as_const

Aus cppreference.com
<tbody> </tbody>
definiert in Header <utility>
template <class T> constexpr std::add_const_t<T>& as_const(T& t) noexcept;
(1)
template <class T> void as_const(const T&&) = delete;
(2)
1) Erzeugt aus einem lokalisierbaren Wert eine Referenz auf eine konstante vom Typ t
2) Die Überladung für lesbare Werte ist gelöscht worden, um die Benutzung von lesbaren Argumenten zu verbieten

Mögliche Implementierung

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

Anmerkungen

Feature testing macro: __cpp_lib_as_const

Beispiele

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


Referenzen