Jim Jim - 1 year ago 58
C++ Question

C++ How do I make a function/variable local to a namespace?

I want to neatly declare functions and variables local to a namespace, so only namespace members can access them.

In lua, I would use a "local" keyword to do this (in a file/function). Is anything related possible in C++?


Here's a pseudo-c++ sample of my code:

namespace wld {
const int wldDivis = 4;
void myFunc(){
// wldDivis constant used here
void myFunc2(){
// wldDivis also used here

// Somewhere later

The variable "wldDivis" is only ever used in namespace wld. How do I localize/"make it invisible" to outside namespace wld, as a "enforced opacity" if others might screw with the inner workings of my functions? Is a namespace well suited?

IE cannot be accessed outside the namespace?

Answer Source

AFAIK there is no access restriction in namespaces in C++.

namespace foo {
    void local_func() {}

    // local_func can be accessed inside the namespace

    void global_func() { local_func(); }

// ...

foo::local_func(); // local_func can be accessed outside the namespace

You can achieve something close with static member functions inside a class definition:

class foo {
        static void local_func() {}

        // local_func can be accessed inside the "namespace" of the class

        void global_func() { local_func(); }

// ...

foo::local_func(); // error : local_func is private to the class
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download