std::bad_any_cast
來自 cppreference.com
定義於標頭檔案 <any> |
||
class bad_any_cast : public std::bad_cast; |
(C++17 起) | |
定義一個物件型別,當 std::any_cast 的值返回形式失敗時丟擲。
目錄 |
[編輯] 成員函式
(建構函式) |
構造一個新的 bad_any_cast 物件(公開成員函式) |
operator= |
替換 bad_any_cast 物件(公開成員函式) |
what |
返回解釋字串 (公開成員函式) |
std::bad_any_cast::bad_any_cast
bad_any_cast() noexcept; |
(1) | (C++17 起) |
bad_any_cast( const bad_any_cast& other ) noexcept; |
(2) | (C++17 起) |
構造一個新的 bad_any_cast
物件,其中包含一個實現定義的以 null 結尾的位元組字串,可以透過 what() 訪問。
1) 預設建構函式。
引數
其他 | - | 要複製的另一個異常物件 |
std::bad_any_cast::operator=
bad_any_cast& operator=( const bad_any_cast& other ) noexcept; |
(C++17 起) | |
將內容賦值為 other 的內容。如果 *this 和 other 都具有動態型別 std::bad_any_cast
,則賦值後 std::strcmp(what(), other.what()) == 0。
引數
其他 | - | 用於賦值的另一個異常物件 |
返回值
*this
std::bad_any_cast::what
virtual const char* what() const noexcept; |
(C++17 起) | |
返回解釋字串。
返回值
指向一個實現定義的以 null 結尾的字串的指標,其中包含解釋性資訊。該字串適合轉換為 std::wstring 並顯示。保證該指標在獲取它的異常物件被銷燬之前,或者在呼叫異常物件的非 const 成員函式(例如複製賦值運算子)之前是有效的。
在常量求值期間,返回的字串使用普通字面量編碼進行編碼。 |
(C++26 起) |
注意
允許但不要求實現重寫 what()
。
繼承自 std::bad_cast
[編輯] 示例
執行此程式碼
#include <any> #include <cassert> #include <print> int main() { auto x = std::any(42); assert(std::any_cast<int>(x) == 42); // OK try { [[maybe_unused]] auto s = std::any_cast<std::string>(x); // throws } catch (const std::bad_any_cast& ex) { std::println("{}", ex.what()); } }
可能的輸出
bad any_cast