std::any_cast
提供: cppreference.com
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>> とすると、
目次 |
[編集]引数
operand | - | 対象の 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
がヌルポインタでなく、要求された T
の typeid
が operand
の内容の typeid
と一致する場合、 operand に格納されている値を指すポインタ。 そうでなければ、ヌルポインタ。[編集]例外
[編集]例
Run this code
#include <string>#include <iostream>#include <any>#include <utility> int main(){// 単純な例 auto a =std::any(12); std::cout<< std::any_cast<int>(a)<<'\n'; try{std::cout<< std::any_cast<std::string>(a)<<'\n';}catch(conststd::bad_any_cast& e){std::cout<< e.what()<<'\n';} // ポインタの例 if(int* i = std::any_cast<int>(&a)){std::cout<<"a is int: "<<*i <<'\n';}elseif(std::string* s = std::any_cast<std::string>(&a)){std::cout<<"a is std::string: "<<*s <<'\n';}else{std::cout<<"a is another type or unset\n";} // 高度な例 a =std::string("hello"); auto& ra = std::any_cast<std::string&>(a);//< 参照 ra[1]='o'; std::cout<<"a: "<< std::any_cast<conststd::string&>(a)<<'\n';//< const 参照 auto b = std::any_cast<std::string&&>(std::move(a));//< 右辺値参照 // 注: 「b」はムーブ構築された std::string であり、// 「a」は有効だけれども未規定な状態になります。 std::cout<<"a: "<<*std::any_cast<std::string>(&a)//< ポインタ<<"b: "<< b <<'\n';}
出力例:
12 bad any_cast a is int: 12 a: hollo a: b: hollo