std::as_const
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Defined in header
<utility>
template< class T >
constexpr std::add_const_t <T>& as_const( T& t ) noexcept;
(1)
(since C++17)
constexpr std::add_const_t <T>& as_const( T& t ) noexcept;
template< class T >
void as_const( const T&& ) = delete;
(2)
(since C++17)
void as_const( const T&& ) = delete;
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] Notes
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_as_const |
201510L |
(C++17) | std::as_const
|
[edit] Example
Run this code
#include <cassert> #include <string> #include <type_traits> #include <utility> 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)(C++11)(C++11)
(class template) [edit]
(C++11)(C++11)(C++11)
(class template) [edit]