std::as_const(3)
hey bestie!! welcome to the std::as_const(3) page from the C++ Standard Libary (yes bestie, that's how the header spells it π) π no cap, this one is a tiny utility with big βdo not touch my stuffβ energy. letβs gooo π«Ά
π NAME π
std::as_const - std::as_const (bestie, the name is literally the name ππ
)
β¨ Synopsis β¨
okay so here's the signature tea ββ¨ it lives in <utility> and it's been here (since C++17):
Defined in header <utility>
template< class T > (1) (since C++17)
constexpr std::add_const_t<T>& as_const( T& t ) noexcept;
template< class T > (2) (since C++17)
void as_const( const T&& ) = delete;
- Forms an lvalue reference to the
consttype oft. π - The
constrvalue reference overload is= deleted to disallow rvalue arguments. π«
π§ Possible implementation π§
here's the possible implementation, and yes it's giving βone line of actual workβ π:
template<class T>
constexpr std::add_const_t<T>& as_const(T& t) noexcept
{
return t;
}
π Notes π
feature-test macro check, bestie β all the deets:
- Feature-test macro:
__cpp_lib_as_const - Value:
201510L - Std:
(C++17) - Feature:
std::as_const
π Example π
// Run this code β literally run it, it's cute π
#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.");
}
π See also π
the see-also squad is a little squished in the original, so here's every entry and every marker, fr fr:
is_constβ checks if a type is const-qualified;(C++11);(class template)add_cvadd_constadd_volatileβ adds const and/or volatile specifiers to the given type- markers from the original around that add group:
(C++11),(class template),(C++11),(C++11) remove_cvremove_constremove_volatileβ removes const and/or volatile specifiers from the given type- markers from the original around that remove group:
(C++11),(class template),(C++11),(C++11) ranges::as_const_viewβ converts a view into aconstant_rangeviews::as_const- markers from the original around that pair:
(class template),(range adaptor object),(C++23)
okay that's the whole page bestie!! huge credit to http://cppreference.com, dated 2024.06.10, and the std::as_const(3) manual page β mwah πβ¨π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms