Namespace friend functions C++

  • Thread starter shwanky
  • Start date
43
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?
 
73
0
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
 

Related Threads for: Namespace friend functions C++

  • Posted
Replies
2
Views
6K
  • Posted
2
Replies
36
Views
3K
  • Posted
Replies
9
Views
2K
Replies
1
Views
2K

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top