std::as_const
Von de.cppreference.net
< cpp | Dienstprogramme
| Definiert in Header <utility>
|
||
template< class T >
constexpr std::add_const_t<T>& as_const( T& t ) noexcept;
|
(1) | (seit C++17) |
template< class T >
void as_const( const T&& ) = delete;
|
(2) | (seit C++17) |
1) Bildet einen Lvalue-Referenz auf const-Typ von
t.2) Die const-Rvalue-Referenz-Überladung ist gelöscht, um Rvalue-Argumente zu verbieten.
Mögliche Implementierung
template<class T> constexpr std::add_const_t<T>& as_const(T& t) noexcept { return t; } |
Hinweise
| Feature-Test Makro | Wert | Std | Feature |
|---|---|---|---|
__cpp_lib_as_const
|
201510L
|
(C++17) |
std::as_const
|
Beispiel
Diesen Code ausführen
#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(); // Fehler: 'constRef' ist 'const'-qualifiziert, // aber 'clear' ist nicht als const markiert 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."); }
Siehe auch
|
(C++11)
|
prüft, ob ein Typ const-qualifiziert ist
(Klassentemplate) |
|
(C++11)
(C++11)
(C++11)
|
fügt
const
und/oder
volatile
Spezifizierer zum gegebenen Typ hinzu
(Klassentemplate) |
|
(C++11)
(C++11)
(C++11)
|
entfernt
const
und/oder
volatile
Spezifizierer vom gegebenen Typ
(Klassentemplate) |
konvertiert eine
view
in einen
constant_range
(Klassentemplate) (Range-Adapter-Objekt) |