Files
cppdraft_translate/cppdraft/any/nonmembers.md
2025-10-25 03:02:53 +03:00

4.0 KiB
Raw Blame History

[any.nonmembers]

22 General utilities library [utilities]

22.7 Storage for any type [any]

22.7.5 Non-member functions [any.nonmembers]

🔗

void swap(any& x, any& y) noexcept;

1

#

Effects: Equivalent to x.swap(y).

🔗

template<class T, class... Args> any make_any(Args&&... args);

2

#

Effects: Equivalent to: return any(in_place_type, std::forward(args)...);

🔗

template<class T, class U, class... Args> any make_any(initializer_list<U> il, Args&&... args);

3

#

Effects: Equivalent to: return any(in_place_type, il, std::forward(args)...);

🔗

template<class T> T any_cast(const any& operand); template<class T> T any_cast(any& operand); template<class T> T any_cast(any&& operand);

4

#

Let U be the type remove_cvref_t.

5

#

Mandates: For the first overload, is_constructible_v<T, const U&> is true.

For the second overload, is_constructible_v<T, U&> is true.

For the third overload, is_constructible_v<T, U> is true.

6

#

Returns: For the first and second overload, static_cast(*any_cast(&operand)).

For the third overload, static_cast(std::move(*any_cast(&operand))).

7

#

Throws: bad_any_cast if operand.type() != typeid(remove_reference_t).

8

#

[Example 1: any x(5); // x holds int assert(any_cast(x) == 5); // cast to value any_cast<int&>(x) = 10; // cast to reference assert(any_cast(x) == 10);

x = "Meow"; // x holds const char* assert(strcmp(any_cast<const char*>(x), "Meow") == 0); any_cast<const char*&>(x) = "Harry"; assert(strcmp(any_cast<const char*>(x), "Harry") == 0);

x = string("Meow"); // x holds string string s, s2("Jane"); s = move(any_cast<string&>(x)); // move from any assert(s == "Meow"); any_cast<string&>(x) = move(s2); // move to any assert(any_cast<const string&>(x) == "Jane");

string cat("Meow");const any y(cat); // const y holds string assert(any_cast<const string&>(y) == cat);

any_cast<string&>(y); // error: cannot any_cast away const — end example]

🔗

template<class T> const T* any_cast(const any* operand) noexcept; template<class T> T* any_cast(any* operand) noexcept;

9

#

Mandates: is_void_v is false.

10

#

Returns: If operand != nullptr && operand->type() == typeid(T) is true, a pointer to the object contained by operand; otherwise, nullptr.

11

#

[Example 2: bool is_string(const any& operand) {return any_cast(&operand) != nullptr;} — end example]