名前空間
変種
操作

std::any_cast

提供: cppreference.com
< cpp‎ | utility‎ | any
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
 
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以上)

格納されているオブジェクトへの型安全なアクセスを行います。

Ustd::remove_cv_t<std::remove_reference_t<T>> とすると、

1) std::is_constructible_v<T, const U&>false の場合、プログラムは ill-formed です。
2) std::is_constructible_v<T, U&>false の場合、プログラムは ill-formed です。
3) std::is_constructible_v<T, U>false の場合、プログラムは ill-formed です。

目次

[編集] 引数

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 がヌルポインタでなく、要求された Ttypeidoperand の内容の typeid と一致する場合、 operand に格納されている値を指すポインタ。 そうでなければ、ヌルポインタ。

[編集] 例外

1-3) 要求された Ttypeidoperand の内容の typeid と一致しない場合、 std::bad_any_cast を投げます。

[編集]

#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(const std::bad_any_cast& e) {
        std::cout << e.what() << '\n';
    }
 
    // ポインタの例
 
    if (int* i = std::any_cast<int>(&a)) {
       std::cout << "a is int: " << *i << '\n';
    } else if (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<const std::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