7

I was inspired by the comments under this question.

I didn't see any reason why a class with only static functions would be a better design than a namespace (with just functions). Any list of pros and cons of these two approaches are welcomed. It would be great with some practical examples!

einpoklum
  • 118,144
  • 57
  • 340
  • 684
GuLearn
  • 1,814
  • 2
  • 18
  • 32

2 Answers2

11

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

Outside of that use case, I would stick to a namespace with regular functions.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
3

Classes with static methods

  • You can have class inside another class, you can't have namespace inside class (because it probably does not 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 this is moot point.

  • you can import symbols to another namespaces.

    namespace mystuff { using namespace boost; }

  • you can import selected symbols.

    using std::string;

  • they can span over several files (very important advantage)

  • inline namespaces (C++11)

Bottom line: namespaces are way to go in C++.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71