C/C++ Namespace friend functions C++

  • Thread starter Thread starter shwanky
  • Start date Start date
  • Tags Tags
    C++ Functions
Click For Summary
The discussion revolves around defining a friend function named "sort" for a class called Random, which needs to exist in two separate namespaces: ascending and descending. The challenge arises because the friend function must access the private members of the Random class, but the namespaces need to be declared beforehand. A proposed solution involves using a forward declaration of the Random class and defining the sort functions to take a pointer to Random instead of a reference. This allows the friend functions to be declared within the Random class after the namespaces are defined. Additionally, there is a suggestion that templates could be an alternative approach to achieve the same functionality without using pointers.
shwanky
Messages
43
Reaction score
0
So I have this Class Random that needs to have a friend function sort which needs to exist in two namespaces.

Class Random
{
... Some stuff
friend void sort(Random &x);
}

namespace ascending
{
void sord(Random &x)
{
... Some Stuff
}
}

namespace descending
{
void sort(Random &x)
{
... Some Stuff
}
}


The problem is I need sort to be able to access the private members of the Random class but to define sort I need to have the namespaces ascending and descending already declared... Its a weird circular argument that can't work. My question is, how can I define the Class Random with so that it can have a friend function sort that resides in two namespaces?
 
Technology news on Phys.org
I think that you can do the following.

class Random;

namespace ascending
{
void sort(Random* x)
{
...
}
}

namespace descending
{
void sort(Random* x)
{
...
}
}

class Random
{
friend void ascending::sort(Random* x);
friend void descending::sort(Random* x);
...
};

I think that will work; however, I haven't tried it. You may also be able to do the same sort of thing using templates instead of the forward declaration and pointer usage.

Ken
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 25 ·
Replies
25
Views
2K
  • · Replies 5 ·
Replies
5
Views
1K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 36 ·
2
Replies
36
Views
3K
Replies
20
Views
2K
Replies
89
Views
6K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 34 ·
2
Replies
34
Views
4K