7

我受到这个问题下的评论的启发。

我没有看到为什么一个只有静态函数的类比命名空间(只有函数)更好的设计。欢迎列出这两种方法的优缺点。有一些实际的例子会很棒!

4

2 回答 2

11

一个非风格的区别是您可以使用类作为模板参数,但不能使用命名空间。这有时用于策略类,例如std::char_traits.

在那个用例之外,我会坚持使用具有常规功能的命名空间。

于 2013-04-19T16:02:40.023 回答
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++.

于 2013-04-19T16:05:38.227 回答