C++ policy classes and namespaces - c++

I've implemented a policy-based class. For the moment, the class template and its policy classes are declared in a namespace called utility.
The problem I face is the verbosity of the resulting code. Client code looks like that:
utility::MyTool<utility::AFirstPolicy, utility::ASecondPolicy>
my_function(utility::MyTool<utility::AnotherFirstPolicy, utility::AnotherSecondPolicy>);
Not very readable, as you can see. I would like to get something closer from:
MyTool<AFirstPolicy, ASecondPolicy>
my_function(MyTool<AnotherFirstPolicy, AnotherSecondPolicy>);
I'm wondering what the good practice is in such a case. Here is what I can think of:
Typedef
The most obvious solution. Not very convenient for me because the policies can differ from function to function an bring important information on the function usage. I would like them to appear directly in the function prototype. Moreover, it introduces many type names in several namespaces.
Using directive
Put a using namespace utility; or using utility::MyTool; using utility::AFirstPolicy;, etc. in my file.
The tool is often used in header files from other namespaces, which makes using-directives not very suitable.
Policy classes in global namespace
I don't like this approach especially as policy classes often have vague names that make sense only in their context.
Macro
Use something as
#define MY_TOOL(pcy1, pcy2) utility::MyTool<utility::##pcy1, utility::##pcy2>
to transform the previous code to
MY_TOOL(AFirstPolicy, ASecondPolicy)
my_function(MY_TOOL(AnotherFirstPolicy, AnotherSecondPolicy));
I'm not sure this is more readable. It works only for a fixed number of policies (this is my case: always 2, no default setting) and it does not work if the policy classes themselves take template parameters.
Which of the previous approaches would you recommend to me? Are there "best practices"? Another idea?

If you have a my_function(utility::MyTool<...>), then I would say that my_function belongs to the interface of the class template utility::MyTool<...>. In other words, my_function itself belongs to the namespace utility.
This means that you can write code in the desired shorthand form:
namespace utility {
typedef MyTool<AFirstPolicy, ASecondPolicy> SomeTool;
my_function(SomeTool);
}
You can read more about interfaces and namespaces in this old column "What's In a Class" by Herb Sutter.
Note that even if you want to use functions in other namespaces with classes from namespace utility, you can still reopen that namespace and define the policy class right there and do something like
// SomeHeader.hpp
namespace bla {
// your classes and functions
}
// reopen namespace utility
namespace utility {
typedef MyTool<AFirstPolicy, ASecondPolicy> SomeTool;
}
namespace bla {
typedef utility::SomeTool BlaTool; // or using-declaration
my_function(BlaTool);
}
This is of course more verbose than defining my_function inside the utility namespace, but at least you can assemble all the various policies without too much typing.

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.

Differences between an abstract class with static functions and regular functions in a 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.

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.

Avoiding Over-Use of Namespaces

My library uses several nested namespaces, laid out like the following:
Library name
Class name 1
Class name 2
Class name 3
[...]
Utilities
Class name 1
[...]
Class name 2
[...]
Class name 3
[...]
[...]
The "Utilities" namespace contains useful extensions to each of the classes that don't warrant being included in the actual class itself.
The "Library name" namespace is necessary because it avoids broad conflicts with other libraries, the "Utilities" namespace is necessary to avoid the type of ambiguity that arises from things like this, and the "Class name" namespaces inside it avoid name clashes between utilities written for similar classes.
Despite this, it's still an enormous hassle in practice. Take the following, for example:
MyLibrary::MyContainer<int> Numbers = MyLibrary::Utilities::MyContainer::Insert(OtherContainer, 123, 456);
// Oh God, my eyes...
This makes me think I'm doing something seriously wrong. Is there an easier way to keep things organized, intuitive and unambiguous?
Look at how the standard library (or boost) is organized. Nearly all of it is inside the single std namespace. There's just little to be gained by putting everything inside its own namespace.
Boost puts most things inside boost, while major libraries get a single subnamespace (boost::mpl, or boost::filesystem, for example). And libraries commonly define a single aux subnamespace for internal implementation details.
But you don't typically see deep or fine-grained namespace hierarchies, because they're just painful to work with, and there's little to no benefit from them.
Here are some good rules of thumb:
Helper functions related to a specific class should be in the same namespace as the class, to enable ADL to work. Then you don't need to qualify the name of the helper function at all when calling it. (Like how you can call sort instead of std::sort on iterators defined in std).
For everything else, remember that the purpose of namespaces is to avoid name clashes and not much else. So all your library should be in a namespace, to avoid clashes with user code, but within that namespace, there's no technical need for further subnamespaces unless you plan to introduce clashing names.
You may want to separate internals of your library into a sub-namespace, so users don't accidentally pick them up from the main namespace, similar to Boost's aux.
But generally, I'd suggest as few nested namespaces as possible.
And finally, I tend to make a point of using short, easy-to-type and easy-to-read names for my namespaces (again, std is a good example to follow. Short and to the point, and nearly always without further nested namespaces, so you don't get a cramp from having to write it often, and so it doesn't clutter your source code too much.)
Just the first rule about helper functions and ADL would allow your example to be rewritten like this instead:
MyLibrary::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
Then we could rename MyLibrary to, say, Lib:
Lib::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
and you're down to something pretty manageable.
There shouldn't be any clashes between similar utility functions for different classes. C++ allows you to overload functions, and specialize templates, so that you can have both an Insert(ContainerA) and Insert(ContainerB) in the same namespace.
And of course, clashes between namespaces and classes are only possible if you actually have additional nested namespaces.
Remember that within your Library namespace, you alone dictate which names are introduced. And so you can avoid name clashes just by, well, not creating any clashing names. A namespace to separate user code from library code is important because the two may not know about each others, and so clashes can occur unintentionally.
But within your library, you can just give everything non-clashing names.
If something hurts, stop doing it. There is absolutely no need to use deeply nested namespaces in C++ - they are not intended to be architectural devices. My own code always uses a single level of namespaces.
If you insist on using nested namespaces, you can always create short aliases for them:
namespace Util = Library::Utility;
then:
int x = Util::somefunc(); // calls Library::Utility::somefunc()
A declaration in a header file necessitates the namespacing to not pollute the global namespace:
MyLibrary::Utilities::MyContainer<int> Numbers;
But in the source file you can use usings:
using namespace MyLibrary::Utilities;
...
MyContainer<int> Numbers;
Numbers.Insert(OtherContainer, 123, 456);
The fully qualified name doesn't actually look that bad to me, but I like being explicit in method and class names. But using can help things out:
You could probably get away with a using namespace MyLibrary at global scope in your source files, making it:
MyContainer<int> Numbers = Utilities::MyContainer::Insert(OtherContainer, 123, 456);
And then you can import the specific functions you need:
using MyLibrary::Utilities::MyContainer::Insert
and then
MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);

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.