std::as_const - cppreference.com (original) (raw)
Defined in header | ||
---|---|---|
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) |
Forms lvalue reference to const type of t.
const rvalue reference overload is deleted to disallow rvalue arguments.
[edit] Possible implementation
template constexpr std::add_const_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
#include
#include
#include
#include
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, std::string>,
"ExprType should be some kind of string.");
static_assert(<ExprType, std::string>,
"ExprType shouldn't be a mutable string.");
}