Bug 28597 - friend function defined inside class declaration
Summary: friend function defined inside class declaration
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.1.0
: P3 minor
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2006-08-04 01:38 UTC by nathan
Modified: 2006-08-04 02:17 UTC (History)
1 user (show)

See Also:
Host: x86_64-redhat-linux
Target: x86_64-redhat-linux
Build: x86_64-redhat-linux
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description nathan 2006-08-04 01:38:30 UTC
When a friend function is defined in inside a class,
and then passed to a STL algorithm function,
gcc 4.1 reports it can't find the friend function.

gcc 4.0 and gcc 3.4.4 will compile the following code snippet.
gcc 4.1.0 (Fedora 5 x86-64) won't compile, it returns this error message.

friend_gcc4_bug.cc: In function ‘int main(int, char**)’:
friend_gcc4_bug.cc:32: error: ‘Compare’ was not declared in this scope

But gcc 4.1.0 will compile it if the friend is defined
outside the class, rather than inside.

friend_gcc4_bug.cc:
-------------------

#include <iostream>
#include <vector>
#include <algorithm>

#define FRIEND_IN_CLASS 1

class Class
{
private:
    int     mVal;

#if FRIEND_IN_CLASS
    friend bool Compare( const Class& a, const Class& b )
    {
        return a.mVal < b.mVal;
    }
#else
    friend bool Compare( const Class& a, const Class& b );
#endif
};

#if ! FRIEND_IN_CLASS
bool Compare( const Class& a, const Class& b )
{
    return a.mVal < b.mVal;
}
#endif

int main( int argc, char** argv )
{
    std::vector<Class> vec;
    std::sort( vec.begin(), vec.end(), Compare );
    std::nth_element( vec.begin(), vec.begin(), vec.end(), Compare );
    std::search( vec.begin(), vec.end(),
                 vec.begin(), vec.end(), Compare );

    Class a, b;
    Compare( a, b );
}
Comment 1 Andrew Pinski 2006-08-04 02:17:15 UTC
    friend bool Compare( const Class& a, const Class& b );
Does not inject a function (or class).

Use the following option to get back the ARM (pre standard) behavior:
  -ffriend-injection          Inject friend functions into enclosing namespace