std::any::operator=
Von cppreference.com
| any& operator=( const any& rhs ); |
(1) | (seit C++17) |
| any& operator=( any&& rhs ) noexcept; |
(2) | (seit C++17) |
| template< typename ValueType > any& operator=( ValueType&& rhs ); |
(3) | (seit C++17) |
Weist den enthaltenen Wert zu.
2) Weist den Zustand von rhs durch Verschieben zu, als ob durch std::any(std::move(rhs)).swap(*this). rhs bleibt nach der Zuweisung in einem gültigen, aber nicht spezifizierten Zustand.
3) Weist den Typ und Wert von rhs zu, als ob durch std::any(std::forward<ValueType>(rhs)).swap(*this). Diese Überladung nimmt nur an der Auflösung von Überladungen teil, wenn std::decay_t<ValueType> nicht vom Typ std::any ist und std::is_copy_constructible_v<std::decay_t<ValueType>> true ist.
Inhalt |
[edit] Template-Parameter
| ValueType | - | Typ des enthaltenen Wertes |
| Typanforderungen | ||
-std::decay_t<ValueType> muss die Anforderungen an CopyConstructible erfüllen. | ||
[edit] Parameter
| rhs | - | Objekt, dessen enthaltener Wert zugewiesen werden soll |
[edit] Rückgabewert
*this
[edit] Ausnahmen
1,3) Wirft std::bad_alloc oder eine Ausnahme, die vom Konstruktor des enthaltenen Typs ausgelöst wird. Wenn aus irgendeinem Grund eine Ausnahme ausgelöst wird, haben diese Funktionen keine Auswirkung (starke Ausnahmensicherheitsgarantie).
[edit] Beispiel
Führen Sie diesen Code aus
#include <any> #include <cassert> #include <iomanip> #include <iostream> #include <string> #include <typeinfo> int main() { using namespace std::string_literals; std::string cat{"cat"}; std::any a1{42}; std::any a2{cat}; assert(a1.type() == typeid(int)); assert(a2.type() == typeid(std::string)); a1 = a2; // overload (1) assert(a1.type() == typeid(std::string)); assert(a2.type() == typeid(std::string)); assert(std::any_cast<std::string&>(a1) == cat); assert(std::any_cast<std::string&>(a2) == cat); a1 = 96; // overload (3) a2 = "dog"s; // overload (3) a1 = std::move(a2); // overload (2) assert(a1.type() == typeid(std::string)); assert(std::any_cast<std::string&>(a1) == "dog"); // The state of a2 is valid but unspecified. In fact, // it is void in gcc/clang and std::string in msvc. std::cout << "a2.type(): " << std::quoted(a2.type().name()) << '\n'; a1 = std::move(cat); // overload (3) assert(*std::any_cast<std::string>(&a1) == "cat"); // The state of cat is valid but indeterminate: std::cout << "cat: " << std::quoted(cat) << '\n'; }
Mögliche Ausgabe
a2.type(): "void" cat: ""
[edit] Siehe auch
konstruiert ein any-Objekt(public member function) |