Question

Lets say I have a bunch of free functions, within a particular namespace, which are covered by unit-tests. And lets say I see some common functionality that can be moved out into a separate free function. What can I do such that this new function becomes hidden? In other words, this function should only be used by the aforementioned free functions and not elsewhere. Should I added it to a namespace under the free functions' namespace. If so, what should I call the namespace - is there a naming convention?

I should also point out that this new function is not unit tested since it is used internally by other functions that are unit-tested. Perhaps I'm being lazy and the solution to this question is that I simply unit-test this function also and then people can use it if they want.

Was it helpful?

Solution

You can hide it: make it a private static member function of a class, and then explicitly friend each of your inline functions. The implementation could be in- or out-of-line, access control will still work.

Unless you need to restrict access though, I'd follow the Boost convention and just put it in a nested namespace called detail (or something similar). This is just intended to document that it is an implementation detail, rather than a stable public interface (and to avoid polluting the namespace, of course).

This also avoids having to explicitly list each free function as a friend.

OTHER TIPS

You could have the helper function as a static function in the private section of a class and then only friend the functions that are allowed to use it.

class Foo
{
    static int helper() {return 0;}
    friend void baz();
};

void baz()
{
    Foo::helper(); //compiles
}

void buz()
{
    Foo::helper(); //doesn't compile
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top