このページはC++26に採用される見込みの言語機能の変更を解説しています。
のちのC++規格でさらに変更される場合があるため関連項目を参照してください。
概要
C++23まで、定数式内での例外送出、そのコードに到達した時点でコンパイルエラーとなっていた。
C++26からは定数式内での例外送出ができるようになり、ユーザーはその例外を捕捉できるようになる。
consteval auto hello(std::string_view input) {
if (input.empty()) {
throw invalid_argument{"empty name provided"}; // C++23: このコードに到達した時点でthrow式側でコンパイルエラー
}
return concat_into_a_fixed_string("hello ",input);
}
const auto a = hello(""); // C++26: 呼び出し側でコンパイルエラー
const auto b = hello("Hana");
try {
const auto c = hello(""); // C++26: 例外を捕捉
} catch (const validation_error &) {
// everything is fine
}
// C++23: concat関数の深い場所にあるthrow式側でコンパイルエラー
// C++26: 呼び出し側で「文字列が長すぎる」のようなコンパイルエラーになる
const auto d = hello("Adolph Blaine Charles David Earl Frederick Gerald Hubert Irvin John Kenneth Lloyd Martin Nero Oliver Paul Quincy Randolph Sherman Thomas Uncas Victor William Xerxes Yancy Zeus");
関連項目
- C++11 constexpr
std::exception
std::nested_exception
std::bad_exception
std::uncaught_exceptions()
std::current_exception()
std::rethrow_exception()
std::make_exception_ptr()
std::throw_with_nested()
std::rethrow_if_nested()
std::bad_alloc
std::bad_array_new_length
std::bad_cast
std::bad_typeid
<stdexcept>
std::bad_expected_access