Is it ok to include all function declarations in the header to create a "private namespace"?

I've been writing code for a while. I've used namespaces to separate multiple pieces of code to make the code more readable. However, I got a problem when I wanted to do something in this private. Here's what I found:

//foobar.h
namespace foo_bar {
  //Other items here...
}

      

//foobar.cpp
namespace foo_bar {
  //Other items here...
  void foo_barz() {..
    //Faked private method!
  }
}

      

Compiled. Is there any negative effect of using this method? I think a class might be a better choice for this, but using a namespace at the time seemed like an easier solution because it was one project. Is there a more "conventional" way to do this? Could this cause other problems in the future? What problems can there be with this?

EDIT: I guess I didn't quite understand what I did. I did it like this: I did not include the function prototype in the header file, so when it is included, the header file makes the code the file was included in to believe the function does not exist.

+3


source to share


1 answer


To make it foo_barz

truly "private" (ie, its name is not accessible from other units), put it in an anonymous namespace, not foo_bar

:

// foobar.cpp

namespace   /* stuff in here is only visible within this unit */
{ 
    void foo_barz() { ...
}

      

If you want to declare this function before defining it, you can add:

namespace 
{
    void foo_barz();
}

      



because multiple unnamed namespaces in the same block actually all refer to the same unnamed namespace.

Another way to achieve the same is to declare the function static:

static void foo_barz() { ...

      

which can run inside or outside the namespace. Some people disapprove of this option (for reasons that I don't understand).

+6


source







All Articles