G ++ 4.5 cannot find friend function

G'day!

I have a question about using friendin C ++. Consider the following code snippet:

#include <ostream>

struct F {
};

struct N {
  friend std::ostream& operator<< (std::ostream&, const N&);
  friend std::ostream& operator<< (std::ostream&, const F&);    
};

void foo(std::ostream &out) {
  F bar;
  out << bar;
}

My understanding has always been that it friendis similar to staticwith the additional property that a function friendhas access to the private part of the class. Under this assumption, the code should compile because there exists operator<<one that accepts ostream&a (const) as well F&.

G ++ 4.0 seems to share my thoughts on this, as it accepts this code. However, the much newer g ++ 4.5 (.2) rejects the code with the message:

ns.cc: In function 'void foo(std::ostream&)':
ns.cc:14:10: error: no match for 'operator<<' in 'out << bar'

is g ++ 4.5 wrong or am i (and g ++ 4.0) wrong?

( F , operator<< N.)

,

+3
3

. gcc 4.4.

#include <ostream>

struct F {
};

struct N {
  friend std::ostream& operator<< (std::ostream&, const N&);
  friend std::ostream& operator<< (std::ostream&, const F&);    
};

std::ostream& operator<< (std::ostream&, const N&);
std::ostream& operator<< (std::ostream&, const F&);    

void foo(std::ostream &out) {
  F bar;
  out << bar;
}
+4

, , .

struct N {
   friend void func1() { }
   friend void func2();
   friend void func3();
};

void func3();

func1(); /* OK */
func2(); /* not OK */
func3(); /* OK */
+5

(FCD, n3242),

[class.friend] :

6) , (9.8), , .

7) . , , () , . , , (3.4.1).

9) , , , .

, ?

struct F {
};

struct N {
  friend std::ostream& operator<< (std::ostream&, const F&);    
};

operator<< N. ​​ ( ). , 7 , N.

operator<<, :

void foo(std::ostream &out) {
  F bar;
  out << bar;
}

( , , ).

:

  • use 7: define the inline function following the friend declaration.
  • use 9: also declare a function in the namespace

Due 4though:

4) The function declared in the friend’s declaration has an external binding (3.5). Otherwise, the function retains the previous relationship (7.1.1).

I would recommend declaring it before the announcement friendin order to control its connection, but this rarely matters.

0
source

Source: https://habr.com/ru/post/1613915/


All Articles