Boost logo

Boost :

Subject: Re: [boost] Implicit Convert from own Typ to Boost::Variant Type
From: Jeffrey Lee Hellrung, Jr. (jhellrung_at_[hidden])
Date: 2011-02-11 14:30:58


On 2/10/2011 11:44 PM, a.mueller wrote:
> Hi,
> i'm new here and i hope you can help me.
> My problem i have a class with a Boost Variant type as member and a implicit convert operator from my class to this Variant type. But when i want use the conversion in my programm the Compiler give me a error.
> Compiler Version gcc 4.4.1 on Ubuntu system
> Boost version 1.45
> Example Program:
> #include<iostream>
>
> #include<boost/variant.hpp>
>
> #include<boost/lexical_cast.hpp>
>
> using namespace std;
>
>
>  
>
> typedef boost::variant<float,int> Testtyp;
>
> class Testtypcontainer
>
> {
>
> public:
>
> Testtypcontainer():m_testtyp((float) 5.5){}
>
> Testtyp m_testtyp;
>
> template<class T>
>
> void settesttyp(T testvalue){m_testtyp =testvalue;}
>
> Testtyp gettesttyp(){return m_testtyp;}
>
> operator Testtyp() const{
>
> return m_testtyp;
>
> }
>
> };
>
>
> int main(){
>
> Testtyp help1;
>
> Testtypcontainer help3;
>
> cout<<help3.gettesttyp()<<endl;
>
> help1=(Testtyp)help3; // generate compile error
>
>
> return 0;
>
> }
>
> P.s. Sorry for my bad english

Looks like the compiler translates your C-style cast

help1=(Testtyp)help3;

into a call to the constructor

template< class T >
variant< float, int >::variant(T&)

rather than using Testtypcontainer's conversion operator. This could
probably be fixed by SFINAE'ing out certain bindings of T in the variant
constructor, i.e., using boost::enable_if to only allow T to be bound
such that T& (and const T& for the other constructor overload) is
(uniquely?) convertible to one of the variant's types (in this case,
float and int).

I would file a trac ticket, maybe simplify your example code:

#include <boost/variant.hpp>

typedef boost::variant<int> variant_t;

struct X
{ operator variant_t() const { return variant_t(); } };

void main()
{
     X x;
     variant_t v = static_cast< variant_t >(x); // COMPILER ERROR
}

and, if you wish and are able to, submit a patch.

- Jeff


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