Boost logo

Boost :

Subject: Re: [boost] Implicit cast rules
From: Krzysztof Czainski (1czajnik_at_[hidden])
Date: 2011-05-24 08:41:02


2011/5/24 Gregory Crosswhite <gcross_at_[hidden]>

> Hey everyone,
>
Hi Greg

>
> Would someone please explain to me the implicit cast rule that prevents the
> following from compiling, and/or if there is a way around it?
>
> #include <boost/optional.hpp>
> #include <iostream>
>
> using namespace boost;
> using namespace std;
>
> struct C {
> operator optional<int>() { return none; }
> };
>
> int main() {
> C c;
> cout << static_cast<optional<int> >(c) << endl;
> return 0;
> }
>
> Error message:
>
> In file included from /usr/include/boost/optional.hpp:15,
> from cast-to-optional.cpp:1:
> /usr/include/boost/optional/optional.hpp: In member function ‘void
> boost::optional_detail::optional_base<T>::construct(const Expr&, const
> void*) [with Expr = C, T = int]’:
> /usr/include/boost/optional/optional.hpp:262: instantiated from
> ‘boost::optional_detail::optional_base<T>::optional_base(const Expr&, const
> Expr*) [with Expr = C, T = int]’
> /usr/include/boost/optional/optional.hpp:559: instantiated from
> ‘boost::optional<T>::optional(const Expr&) [with Expr = C, T = int]’
> cast-to-optional.cpp:13: instantiated from here
> /usr/include/boost/optional/optional.hpp:392: error: cannot convert ‘const
> C’ to ‘int’ in initialization
>
> I can tell what is happening; it would seem that the implicit cast rule
> selects the optional() constructor before it even looks at my more specific
> cast operator. I'm just confused about why this should be, since I see no
> reason why constructor casts should be prioritized over operator casts. Is
> this just the way it is, a GCC quirk, something I'm doing wrong, etc?
>

The compiler sais "cannot convert 'const C' to 'int'. I think it means
static_cast<> takes c as a const, and your conversion operator is not a
const member, so the compiler cannot use it. Solution (not tested):

operator optional<int>() const { return none; }

Regards
Kris


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk