c++17 namespaces, is it possible to force qualified access ALWAYS? - c++

to my surprise, when a function is declared in the same namespace as a variable, the function may access that variable without qualification.
// file qqq.cpp
namespace aaa {
void f();
int x;
}
void aaa::f() {
aaa::x; // 0. INTENDED ACCESS to x in namespace aaa (also works)
x; // 1. SURPRISE: x can be accessed without aaa:: qualification
bool x; // 2. SURPRISE: given (1) why is it allowed to redefine x?
}
question:
A) is there any way to ensure that all objects in a namespace be blind to its fellow constituents, and to require access always through :: ?
B) if not, what would be the correct coding practice to obtain the desired behavior?
C) if not, an alternative solution would be to separate the each namespace into 2, one for functions and another for variables, like f_aaa and v_aaa. but this seems quite clunky and ugly in practical use, eg. void f_sqlite::myfun() { v_sqlite::myvar; } instead of just void sqlite::myfun() { sqlite::myvar; }
edit 1: context, the "problem" im trying to solve:
refactoring several thousand lines of code, namespaces was thought to be suitable for bundling related elements, eg. an "sqlite" namespace for sqlite utility functions and variables used throughout the code base. forced access through :: would be an excellent way of increasing clarity and avoiding name clashes and hiding. separate namespaces for "one bundle" would defeat the purpose. classes would not seem conceptually appropriate.
edit 2:
D) is it possible to get a WARNING (enable compiler flag) to signal when a function in namespace aaa accesses a variable in namespace aaa without qualification?
edit 3:
i think i will end up using "separate namespaces" anyway, but by way of nested namespaces
// file qqq.cpp
namespace aaa::f { // namespace for functions
void f();
void g();
}
namespace aaa::v { // namespace for variables
int x;
}
// definition of function f inside namespace aaa::f
void aaa::f::f() {
aaa::v::x; // only way of accessing x in aaa::v (good) (ugly)
x; // compiler error (good)
bool x; // normal scope hiding (good)
g(); // works: ARGH! would like to force qualifying with aaa::f::
}
still rather ugly though. and! functions can still call each other unqualified, objects can still call/reference each other unaqulified. would really have been nice to simply be able to put some "force-qualifier" (like "private") on all or some element inside a namespace.

A) is there any way to prevent all objects in a namespace to be blind to its fellow constituents, and to require access always through :: ?
There isn't.
B) if not, what would be the correct coding practice to obtain the desired behavior?
Use a class.
C) if not, an alternative solution would be to separate the aaa namespace into 2, one for functions and another for variables, like f_aaa and v_aaa. but this seems quite clunky and ugly in practical use, eg. void f_sqlite::myfun() { v_sqlite::myvar; } instead of just void sqlite::myfun() { sqlite::myvar; }
Use a class to group relevant functions and data together. What You want to hide put in a private section.

Using a separate (nested) namespace for function and variable is not a good idea. It make the code less readable.
Also always qualifying all names is overkill. If the function f is in namespace aaa then it should really prefer variables from that namespace.
And finally the only reason why you would have such problem is because you are using too much global variables (or long functions) which is really a bad practice because it make the code harder to maintain.
So I recommend you to use to use good coding practices like
small functions (less than a screen)
avoid global variables
object-oriented design using class with member functions and data when appropriate.
small files (so you don't get irrelevant stuff)
avoid variables in header files
include only the files you really need (thus you won't get many conflicts if any)
In fact, if you really have the issue you have, it is because current code is large and don't follow good practices..
Other workarounds in comments and answers might works but better to validate if your design is adequate and refactor your code as appropriate.
Extra points:
Another thing that might cause lot of ambiguities is to use basic data type when you should really use custom types.
Uses typed enumeration (enum class) when you want to use some constant for specific parameter instead of define or integers.
Uses class or struct if you have data that are bundled together and are used all over the application.
If you use template functions, you might want to carefully consider what kind of data it would allows particularly if you have a common name like open for the function.

Related

Is it bad practice to have a class that requires no objects to be created? [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

Static functions in class or namespace [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

Anonymous namespaces: Are they really that great?

I have been using the static keyword a long time for defining internal linkage. Later, I switched to the C++ style of wrapping local things in anonymous namespaces.
However, now when I have worked with anonymous namespaces for some years, I start to think that static keyword is a lot easier to work with!
A common problem is that I have this pattern:
namespace {
// ...five pages of code...
} // namespace
To see if a certain function has internal or external linkage, I now have to scroll a lot, as opposed to the old C style where I could just check if the function/object had static in front of it.
I know there are things anonymous namespaces do that static can't - hide typedefs - but personally I'm not really very interested in that, anyway.
What are your take on this? Is the win of anonymous namespaces that great that it warrants the decreased readability? Or am I all out wrong?
If the code in your namespace is too long, there's nothing to stop you doing this:
namespace {
int foo(char* x) {
return x[0] + x[1];
}
}
namespace {
int bar(char *x, char *y) {
return foo(x) + foo(y);
}
}
In C++03 the practical advantage of using an unnamed namespace is precisely that the contents have external linkage, (but are still invisible outside the TU because there's no way to refer to them). Template parameters can't have internal linkage:
namespace {
int foo(const char* x) {
return x[0] + x[1];
}
}
static int foo2(const char *x) {
return x[0] + x[1];
}
template <int (*F)(const char*)>
void baz(const char *p) {
F(p);
}
int main() {
baz<foo>("ab"); // OK
baz<foo2>("ab"); // not valid
}
Apart from the very valid points noted by Steve I see other very important aspects in anonymous namespaces that make them superior to static functions:
Locality, ease of refactoring and information hiding.
Assume you have one or two class function that require several other helper functions which are quite specific but do not use class members. If you stick with Robert C. Martin (Functions should be small and serve one well defined purpose) you will often find that large functions can be refactored into smaller ones although these smaller ones might in the beginning only be used in the former big function.
So what Options do you have:
Make a new (perhaps private) class immediately:
This entails quite a lot of typing might be overkill and -lets face it- everybody
is sometimes lazy or in a hurry.
Generate private static functions or non-member functions:
Both entails editing the header file and the cpp file if you do it
properly, so still a little burden that might interrupt your
workflow more than necessary and generates code that unnecessarily
clutters your header file, might necessitate forward declarations or
even additional includes in your header.
Anonymous namespace:
You have a helper function that does not need
member access and serves one purpose -> Put it there and write this
function close to the class methods where it will be used. This is by large
my preferred one:It's quick and it does not clutter the header file.
The namespace clearly states: this is not used by anything else than this cpp. No
friend will use it and no library user will ever know it's existence. You
can hardly be more obvious and often this paradigm will lead to
cleaner function design which is few input parameters and only one
output modified. Further you have function locality: Define just before primary
use. While this might be a drawback I find it quite help ful when browsing the
implementations of large classes. Another advantage is constants that span several
functions but are not really interesting for a library user. Put them in the
namespace as well, best in the same with the functions that use them. If it turns
out later that you need the constants and the functions elsewhere, transform the
whole into a class, its already neatly packed.
Disclaimer: Many people might argue that the use of a pimpl is by far cleaner. This is just my personal opinion.
An anonymous namespace is the only thing that does not let a class declaration pollute the global scope. Very useful when defining a class in a .cpp file.

c++ Namespace headaches

Okay, this question has evolved a bit, and I want to try to start (over) with the basic goals I'm shooting for:
Create library code that wrappers legacy C-language entities in C++ resource acquisition is initialization and also provides basic or better exception guarantee.
Enable clients of this code to use it in a very natural C++ fashion w/o creating a lot of overhead to existing code to convert it to use the C++ wrapper objects (i.e. automatic conversion to appropriate legacy types, constructors that take legacy types, etc.)
Limit the namespace impact of the library code. Ideally, The library would have several sub-namespaces that provide related functionality that limit the volume and impact of using namespace X type declarations - much as the boost libraries do (i.e. use of details namespaces to only inject those symbols that the user would reasonably want to use, and hide those that are implementation details; also limit the extent of possible new meanings to existing symbols, to avoid surprising implicit conversions within user-code)
Require that clients explicitly ask for those parts of the library that they actually want to inject into their code base. This goes hand in hand with limiting the impact of inclusion of the the library's headers. The client code should have a reasonable level of control over which parts of the library are going to be automatically used for name-resolution when they compile their code.
My own library code should not have to be riddled with refactor-brittle code constructs. It would be ideal if the library's headers didn't have to constantly declare private typedefs in order to have access to the rest of that section of the library. Or in other words: I want my library to be able to be written as intuitively as my clients get to when making use of said library. Name resolution should include the namespace that the library is defined within in addition to any others that have been explicitly "using'd".
I come across this scenario often, and am looking for a better way...
I have a class, C in namespace N. C has a member, Free. It free's something that C manages, and allows C to manage a new thing.
There are several global Free functions. There are also a few helper functions in the same namespace N as C, one of which is a helper that free's the thing managed by C, named free.
So we have something like:
namespace N {
void free(THING * thing);
class C
{
public:
... details omitted...
free()
{
free(m_thing); // <- how best to refer to N::free(THING&)
}
}
} // namespace N
I could use N::free(m_thing). But that seems unfortunate to me. Is there no way to refer to that which is outside the class scope but without resolving absolute namespace (a relative one step out scope-wise)?
It seems to me that having to name N::free is obnoxious, since you wouldn't have to if this were a free-standing function. Nor would you need to if the class's method name happened to be different (e.g. dispose). But because I've used the same name, I cannot access it without having to specify what amounts to an absolute path - rather than a relative path - if you'll indulge me the analogy.
I hate absolute paths. They make moving things around in namespaces very brittle, so code-refactoring becomes much uglier. Plus, the rules of how to name things in function bodies becomes more complex with the current set of rules (as I understand them) - less regular - inducing a schism between what one expects and what one gets as a programmer.
Is there a better way to access free-standing functions in the same namespace as a class without having to absolutely name the free-function absolutely?
EDIT:
Perhaps I should have gone with a less abstract example:
namespace Toolbox {
namespace Windows {
// deallocates the given PIDL
void Free(ITEMIDLIST ** ppidl);
class Pidl
{
public:
// create empty
Pidl() : m_pidl(NULL) { }
// create a copy of a given PIDL
explicit Pidl(const ITEMIDLIST * pidl);
// create a PIDL from an IShellFolder
explicit Pidl(IShellFolder * folder);
...
// dispose of the underlying ITEMIDLIST* so we can be free to manage another...
void Free();
};
So ITEMIDLIST* come from a variety of places, and are destroyed with CoTaskMemFree(). I could introduce Pidl as a global name - as well as all of the helper functions in the "Windows Shell.h" header that is part of my toolbox library.
Ideally, I would segment some of the tools in my library by what they relate to - in this case the above all relates to COM programming in Windows. I have chose Toolbox as the base namespace for my libraries stuff, and was currently thinking I'd use Toolbox::Windows for very windows-y functions, classes, etc.
But the C++ namespace and name-resolution rules seem to make this very difficult (hence this question). It makes it very unnatural to create such segmentation of my code - since koenig lookup fails (since ITEMIDLIST is not in my Toolbox::Windows namespace), and I don't have the ability to move it there! Nor should I. The language should be flexible enough, IMO, to both allow for extension libraries such as my Toolbox library to extend other folks code without having to inject my extensions into their namespace (which, in the case of Win32 and the general vast majority of code that exists today, is the GLOBAL NS - which is the whole point of making namespaces in the first place: to avoid global NS crowding / pollution / ambiguity / programming surprises).
So, I come back around to, Is there a better way to do this: Extend existing libraries of code while not polluting their NS with my extensions but still allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Another Thought: Perhaps what would satisfy my above criterea would be if I had the following:
using namespace X {
code here...
}
Where I could place such a construct anywhere, including in a header, and I would not have to be concerned about dragging X into my client's code, but I would have the same freedom to write my source code as I would if I were in the root namespace.
I don't see to avoid having to qualify namespace-scope free() here, but it should be noted that this is not the same as an "absolute path". For one thing, if you have nested namespaces, you only have to refer to the innermost one:
namespace N1 {
namespace N2 {
namespace N3 {
void free(THING * thing);
class C {
public:
free() {
N3::free(m_Thing); // no need to do N1::N2::
}
};
}
}
}
[EDIT] in response to edited question. Again, I do not see any way to do this in the exact scenario that you describe. However, it doesn't seem to be idiomatic C++ approach - the more common way to do the same is to provide your own wrapper class for ITEMIDLIST that manages all allocations, RAII-style, and exposes the original handle (e.g. via conversion operators a la ATL, or an explicit member function like c_str() if you want extra safety). That would remove the need for your free altogether, and for any other free function that you might want there, since you control the wrapper type and the namespace it's in, you can use ADL as usual.
[EDIT #2]. This part of the question:
allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Isn't this precisely what you putting it in a namespace, and your client writing using namespace ..., will achieve?
You have two options:
Fully qualify function name.
Let Koenig lookup do the job (if THING belongs to namespace N).
I'd choose the first one with such popular function name as free.
Alternate option is to use m_thing->Release() or something like that.
Yuu could write ::free(m_thing);. This will call the global free() function. However, if you have another free() function outside the N namespace, you've got yourself into trouble. Either change names of some of your functions or use the function name with explicit namespace.
It seems to me that there is a problem of design here.
I find strange to have the same identifier used both as a free-function and a class method, it really is confusing. I try to minimize the occurence as much as possible, although I admit that it happens for swap...
I try not to qualify the names within the method, but here of course you run the risk of hiding, where MyClass::free hides the N::free method, which never participates in the lookup... tried to find about the scope resolution here but could not find the exact passage.
For swap I simply use:
class MyClass
{
void swap(MyClass& rhs)
{
using std::swap; // Because int, etc... are not in std
swap(m_foo, rhs.m_foo);
swap(m_bar, rhs.m_bar);
}
};
inline void swap(MyClass& lhs, MyClass& rhs) { lhs.swap(rhs); }
Therefore I make sure that the right method will be included in the lookup, and avoid falling back on a 'global' method if any.
I prefer this approach to explicit naming and usually bolts using and typedef declaration at the top of the method so that the actual code is not bloated.
I would use a completely different approach to what you are trying to accomplish. I think you need a bit of redesigning. Remove the globals and make a factory/abstract factory that will fabricate (create an instance of your class) and destroy it with the destructor. In fact, that would be the RAII idiom.

Namespace + functions versus static methods on a class

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.