[Bug c++/31419] New: template user defined conversion operator instantiated for conversion to self

james dot kanze at gmail dot com gcc-bugzilla@gcc.gnu.org
Sun Apr 1 13:26:00 GMT 2007


The following code does not compile:
------------------templcvt.cc----------------
extern int f( int ) ;

class B
{
public:
    template< typename T >
        operator T const& () const
    {
        return f( 42 ) ;
    }
} ;

B
g()
{
    return B() ;
}
---------------------------------------------
When invoking "g++ -c templcvt.cc", the compiler outputs the
following error messages:

    templcvt.cc: In member function 'B::operator const T&() const [with T =
B]':
    templcvt.cc:24:   instantiated from here
    templcvt.cc:17: error: invalid initialization of reference of type 'const
B&' from expression of type 'int'

Apparently, it is instantiating the template conversion operator
in order to bind the temporary object to the B const& argument
of the (implicit) copy constructor.  This dispite §12.3.2.1 "A
conversion function is never used to convert a (possibly
cv-qualified) object to the (possibly cv-qualified) same object
type (or a reference to it),[...]" (and the fact, of course,
that a function template should only be instantiated if the
function is used).

There's a simple work-around: just define an explicit:

    operator B const&() const { return *this ; }

as well.  But this shouldn't be necessary.

(See also the discussion in comp.std.c++:
http://groups.google.com/group/comp.std.c++/browse_frm/thread/32139b794c433839/#)


-- 
           Summary: template user defined conversion operator instantiated
                    for conversion to self
           Product: gcc
           Version: 4.1.2
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: james dot kanze at gmail dot com
 GCC build triplet: x86_64-unknown-linux-gnu
  GCC host triplet: x86_64-unknown-linux-gnu
GCC target triplet: x86_64-unknown-linux-gnu


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31419



More information about the Gcc-bugs mailing list