Bug Vanquisher

7 April 2008

Analyze This!

Filed under: Bugz, C++ — Tanveer Badar @ 1:06 AM

Consider this little piece of ****. I mean piece of code. :)

template< typename U , typename T > U convert( T t )
{
    return t;
}

template< typename T , typename projection , > class blah_blah_blah
{
public:
    // details we really shouldn’t see

    projection& operator * ( )
    {
        return convert< projection >( *current );
    }
};

If you decide to do

blah_blah_blah< float , double > x = get_blahblahblah( );
*x;

The second statement will fail with some cryptic error message. The real problem is the return type of operator * and the statement return t; in convert. The implicit conversion from T to projection (which is to say, promotion from float to double) loses the l-value[dness] of *current. And since a reference requires l-value upon return, it fails to compile.

Given the constraint the convert< projection > was absolutely necessary, and upon further thought, that projection& was not a requirement, a fix was born.

projection operator * ( )
{
    return convert< projection >( *current );
}

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: