Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Namespace friend functions C++

  1. Oct 16, 2007 #1
    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?
     
  2. jcsd
  3. Oct 29, 2007 #2
    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
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Namespace friend functions C++
  1. Trigama Function in C (Replies: 1)

  2. C gets function (Replies: 7)

  3. C++ Friend Functions (Replies: 2)

Loading...