c++ - bad_variant_access not working -
i trying std::bad_variant_access exception when variant not in list .but below code doesn't work returns implicit converted ascii int value
what changes should variant strict on type selection
#include <iostream> #include <variant> using namespace std; struct printer { void operator()(int x) { cout << x << "i"<<endl; } void operator()(float x) { cout << x << "f"<<endl; } void operator()(double x) { cout << x << "d" << endl;; } }; int main() { using my_variant = std::variant<int, float, double>; my_variant v0('c'); try { std::visit(printer{}, v0); } catch(const std::bad_variant_access& e) { std::cout << e.what() << '\n'; } return 0; } output:
99i
whereas expecting std::bad_variant_access exception
std::visit trigger bad_variant_access exception if variant valueless_by_exception (c++17, see n4659 23.7.3.5 [variant.status] )
what means if tried set variant value in fashion throws exception, variant left in "valueless" state, visitation not permitted.
to trigger it, can change code so:
struct s{ operator int() const{throw 42;} }; struct printer{//as before}; int main() { using my_variant = std::variant<int, float, double>; my_variant v0{'c'}; try{ v0.emplace<0>(s()); }catch(...){} try { std::visit(printer{}, v0); } catch(const std::bad_variant_access& e) { std::cout << e.what() << '\n'; } } demo
frank answered why construct variant in first place using char (construction chosen via overload).
you can not trigger bad_variant_access attempting first construct variant in fashion throw because [variant.ctor] dictates constructor rethrow exception (in case int).
Comments
Post a Comment