std::any::operator=
From ko.cppreference.net
any& operator=( const any& rhs );
|
(1) | (C++17부터) |
any& operator=( any&& rhs ) noexcept;
|
(2) | (C++17부터) |
template< typename ValueType >
any& operator=( ValueType&& rhs );
|
(3) | (C++17부터) |
내용을 포함된 값에 할당합니다.
1)
rhs의 상태를 복사하여 할당합니다. std::any(rhs).swap(*this)을 사용한 것과 같습니다.2)
rhs의 상태를 이동하여 할당합니다. std::any(std::move(rhs)).swap(*this)을 사용한 것과 같습니다. rhs은 할당 후 유효하지만 지정되지 않은 상태로 남습니다.3)
rhs의 타입과 값을 할당합니다. std::any(std::forward<ValueType>(rhs)).swap(*this)을 사용한 것과 같습니다. 이 오버로드는 std::decay_t<ValueType>이 std::any와 동일한 타입이 아니고 std::is_copy_constructible_v<std::decay_t<ValueType>>가 true인 경우에만 오버로드 해결에 참여합니다.템플릿 매개변수
| ValueType | - | 포함된 값 타입 |
| 타입 요구사항 | ||
-
std::
decay_t
<
ValueType
>
는
CopyConstructible
요구사항을 충족해야 합니다.
|
||
매개변수
| rhs | - | 값을 할당할 대상 객체 |
반환값
* this
예외
1,3)
std::bad_alloc
을 던지거나 포함된 타입의 생성자에 의해 던져진 모든 예외를 던집니다.
어떤 이유로든 예외가 발생하면, 이 함수들은 아무런 효과도 가지지 않습니다 (
강력한 예외 안전성 보장
).
예제
이 코드 실행
#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; // 오버로드 (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; // 오버로드 (3) a2 = "dog"s; // 오버로드 (3) a1 = std::move(a2); // 오버로드 (2) assert(a1.type() == typeid(std::string)); assert(std::any_cast<std::string&>(a1) == "dog"); // a2의 상태는 유효하지만 지정되지 않음. 실제로, // gcc/clang에서는 void이고 msvc에서는 std::string임. std::cout << "a2.type(): " << std::quoted(a2.type().name()) << '\n'; a1 = std::move(cat); // 오버로드 (3) assert(*std::any_cast<std::string>(&a1) == "cat"); // cat의 상태는 유효하지만 불확정적: std::cout << "cat: " << std::quoted(cat) << '\n'; }
가능한 출력:
a2.type(): "void" cat: ""
참고 항목
any
객체를 생성합니다
(public member function) |