c++ - Conversion is ambiguous. Standard implicit conversion could not choose cast operator -
i have custom type described
struct { double dbl_; bool boo_; operator double() const { return dbl_; } //operator bool() const { return boo_; } };
and want cast simple types. when operator bool()
undefined a
can implicitly converted simple type int, unsigned, float, etc. operator bool()
conversion ambiguous.
a a; cout << (double) << endl; cout << (float) << endl; //error: conversion 'a' 'float' ambiguous; candidates are: a::operator bool() const; a::operator double() const cout << (int) << endl; // same cout << (char) << endl; // same return 0;
runnable code on cpp.sh
i know few ways fix that:
1.add type conversion operators all expected types.
operator int() const { return (int)dbl_; } // , on...
this looks bad practice.
2.use template restricted types.
template<class t, class...> struct is_any_of: std::false_type{}; template<class t, class head, class... tail> struct is_any_of<t, head, tail...> : std::conditional< std::is_same<t, head>::value, std::true_type, is_any_of<t, tail...> >::type {}; template< class t, class = typename std::enable_if<is_any_of<t, int, float, unsigned, double>::value>::type > operator t() const { if(type_ != type::number) throw node::exception("not number"); return dbl_; }
3.hold bool
value in dbl_
, because 1 of them used. not cool, me.
may more refined solution exists? like
operator bool() const no_implicit_conversation_to_other_types_specifier { return boo_; }
the question @ theory of c++.
upd. no_implicit_conversation_to_other_types_specifier explicit
explicit operator bool() const { return boo_; }
run.
making conversion operators explicit (to prevent implicit conversions) start:
struct { double dbl_; bool boo_; explicit operator double() const { return dbl_; } explicit operator bool() const { return boo_; } };
i'm not sure, imagine prevent ambiguities too.
Comments
Post a Comment