std::any_cast
Определён в заголовочном файле <any> | ||
|---|---|---|
template< class T > T any_cast( const any& operand ); | (1) | (начиная с C++17) |
template< class T > T any_cast( any& operand ); | (2) | (начиная с C++17) |
template< class T > T any_cast( any&& operand ); | (3) | (начиная с C++17) |
template< class T > const T* any_cast( const any* operand ) noexcept; | (4) | (начиная с C++17) |
template< class T > T* any_cast( any* operand ) noexcept; | (5) | (начиная с C++17) |
Выполняет типобезопасный доступ к содержащемуся объекту.
Пусть U будет std::remove_cv_t<std::remove_reference_t<T>>.
1) Программа некорректна, если
std::is_constructible_v<T, const U&> — false.
2) Программа некорректна, если
std::is_constructible_v<T, U&> — false.
3) Программа некорректна, если
std::is_constructible_v<T, U> — false.
4,5) Программа некорректна, если
std::is_void_v<T> — true.Параметры
| операнд | - | целевой объект any |
Возвращаемое значение
1,2) Возвращает
static_cast<T>(*std::any_cast<U>(&operand)).
3) Возвращает
static_cast<T>(std::move(*std::any_cast<U>(&operand))).
4,5) Если
operand не является нулевым указателем, а typeid запрошенного T совпадает с operand, указатель на значение, содержащееся в операнде; в противном случае — нулевой указатель.Исключения
Пример
#include <any>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
int main()
{
// Simple example
auto a1 = std::any(12);
std::cout << "1) a1 is int: " << std::any_cast<int>(a1) << '\n';
try
{
auto s = std::any_cast<std::string>(a1); // throws
}
catch (const std::bad_any_cast& e)
{
std::cout << "2) " << e.what() << '\n';
}
// Pointer example
if (int* i = std::any_cast<int>(&a1))
std::cout << "3) a1 is int: " << *i << '\n';
else if (std::string* s = std::any_cast<std::string>(&a1))
std::cout << "3) a1 is std::string: " << *s << '\n';
else
std::cout << "3) a1 is another type or unset\n";
// Advanced example
a1 = std::string("hello");
auto& ra = std::any_cast<std::string&>(a1); // reference
ra[1] = 'o';
std::cout << "4) a1 is string: "
<< std::any_cast<const std::string&>(a1) << '\n'; // const reference
auto s1 = std::any_cast<std::string&&>(std::move(a1)); // rvalue reference
// Note: “s1” is a move-constructed std::string:
static_assert(std::is_same_v<decltype(s1), std::string>);
// Note: the std::string in “a1” is left in valid but unspecified state
std::cout << "5) a1.size(): "
<< std::any_cast<std::string>(&a1)->size() // pointer
<< '\n'
<< "6) s1: " << s1 << '\n';
}
Возможный вывод:
1) a1 is int: 12 2) bad any_cast 3) a1 is int: 12 4) a1 is string: hollo 5) a1.size(): 0 6) s1: hollo
Отчёты об ошибках
Следующие отчёты об ошибках, изменяющие поведение, были применены ретроактивно к ранее опубликованным стандартам C++.
| Отчёт об ошибке | Применяется к | Опубликованное поведение | Корректное поведение |
|---|---|---|---|
| LWG 3305 | C++17 | поведение перегрузок (4,5) было неясным, если T — void | в этом случае программа некорректна |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/utility/any/any_cast