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

烂漫一生 提交于 2019-12-05 05:54:54

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.

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++.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!