Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a friend function as static?

Tags:

c++

static

friend

Here is some C++ example code that compiles and works fine:

class A { public:    A() {/* empty */}  private:    friend void IncrementValue(A &);    int value; };  void IncrementValue(A & a) {    a.value++; }     int main(int, char **) {    A a;    IncrementValue(a);    return 0; } 

What I would like to do, however, is declare IncrementValue() as static, so that it can't be seen or called from another compilation unit:

static void IncrementValue(A & a) {     a.value++; } 

Doing that, however, gives me a compile error:

temp.cpp: In function ‘void IncrementValue(A&)’: temp.cpp:12: error: ‘void IncrementValue(A&)’ was declared ‘extern’ and later ‘static’ temp.cpp:8: error: previous declaration of ‘void IncrementValue(A&)’ 

... and changing the friend declaration to match doesn't help:

friend static void IncrementValue(A &); 

... as it gives this error:

temp.cpp:8: error: storage class specifiers invalid in friend function declarations 

My question is, is there any way in C++ to have a (non-method) friend function that is declared static?

like image 749
Jeremy Friesner Avatar asked Nov 07 '13 19:11

Jeremy Friesner


People also ask

Can a friend function be static?

The friend function can be a member of another class or a function that is outside the scope of the class. A friend function can be declared in the private or public part of a class without changing its meaning. Friend functions are not called using objects of the class because they are not within the class's scope.

How do you declare a function as static?

A function can be declared as static function by placing the static keyword before the function name. Now, if the above code is compiled then an error is obtained i.e “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file.

What is static friend function in C++?

This function is denoted by using the static keyword. Friend Function: It is basically a function that is especially required for accessing non-public members of the class. It has the right to access all private and protected members of the class.


1 Answers

Quoting N3691 - §11.3/4 [class.friend]

A function first declared in a friend declaration has external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1).

So you need to declare the function as static prior to declaring it as a friend. This can be done by adding the following declarations above the definition of A.

class A;  // forward declaration, required for following declaration static void IncrementValue(A&); // the friend declaration will retain static linkage 
like image 147
Praetorian Avatar answered Sep 23 '22 14:09

Praetorian