Is a class with only static methods preferable to a namespace?

I was inspired by the comments in this question .

I did not see the reasons why a class with only static functions would be better than a namespace (with just functions). Any list of pros and cons of these two approaches is welcome. It would be great with some practical examples!

+4
source share
2 answers

One non-stylistic difference is that you can use the class as a template parameter, but you cannot use the namespace. This is sometimes used for policy classes such as std::char_traits .

Outside of this use case, I will stick with a namespace with regular functions.

+8
source

Classes with Static Methods

  • You can have a class inside another class, you cannot have a namespace inside the class (because it probably doesn't make any sense).
  • They work with very ancient compilers.

Namespaces

- you can create namespace aliases

namespace io = boost::iostreams; Well, you can typedef classes, so that's a moot point.

  • You can import characters into other namespaces.

    namespace mystuff { using namespace boost; }

  • You can import selected characters.

    using std::string;

  • they can span multiple files (a very important advantage)

  • built-in namespaces (C ++ 11)

Bottom line: namespaces are a way to migrate to C ++.

+3
source

All Articles