在C ++中使用命名空间代替静态类? [英] Using a namespace in place of a static class in C++?

查看:375
本文介绍了在C ++中使用命名空间代替静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用命名空间作为静态类是好还是好。例如:

Is it good or okay practice to use a namespace as a static class. For example:

namespace MyStaticFunctions {
    void doSomething();
}

相对:

class MyStaticFunctions {
    static void doSomething();
}

- 编辑 -

我发现很难选择一个答案,因为这么多人是有帮助的。我投票了所有人的答案。感谢一堆!

I found it difficult to pick an answer as so many people were helpful. I've voted up everyones answers. Thanks a bunch!

推荐答案

在C ++中没有一个静态类,所以从C ++的角度来看, 're不使用它作为一个静态类,你使用它作为命名空间。这是肯定接受的做法,使用命名空间将函数组合在一起。

There's no such thing as a "static class" in C++, so from a C++ point of view you're not using it "as a static class", you're using it "as a namespace". It's certainly accepted practice to use namespaces to group functions together.

这取决于你,但是,你想要的组是多大。 C ++库在整个公共接口上使用单个命名空间并不奇怪。对于习惯于(比如说)Java的人来说,这可能是一个惊喜,其中类通常用于将更少数量的静态方法组合在一起。因为C ++在这里是第一个,你可以说Java正在使用类作为命名空间。

It's up to you, though, how big you want the groups to be. It's not unusual for C++ libraries to use a single namespace for the whole public interface. That might come as a surprise to someone who is used to (say) Java, where classes are often used to group together smaller numbers of static methods. Since C++ was here first, you could say that Java is using classes as namespaces.

因此,在C ++中,你不会看到类似 java.util.Collections java.lang.Math ,充满了静态成员。

So, in C++ you don't tend to see classes similar to java.util.Collections or java.lang.Math, full of static members. If you want groups of functions like that in C++, use namespaces.

异常(C ++中并不总是有一个特例)?traits类型如 std :: numeric_limits< T> ,其中模板参数使得类做某些命名空间不能做的事情。您可以定义一个命名空间 numeric_limits 包含函数模板 max< T>() T>()等,但它不是那么好。首先,它对事情稍有不同,类型 T 出现降低层次结构。其次它不做一个traits类型做的一切,因为没有一个对象模板,让你定义一个值 numeric_limits :: digits< T>

The exception (isn't there always a special case in C++?) is traits types like std::numeric_limits<T>, where the template parameter makes the class do something that a namespace can't do. You could define a namespace numeric_limits containing function templates max<T>(), min<T>() etc, but it's not as good. Firstly, it groups things slightly differently, the type T appears "lower down the hierarchy". Secondly it doesn't do everything that a traits type does, because there's no such thing as an "object template" that would let you define a value numeric_limits::digits<T>.

我不知道C#足以评论静态类的实际用法,但AFAIK它只是一个类限制没有非静态成员,因此它类似于那些Java类。

I don't know C# well enough to comment on the practical uses of static classes there, but AFAIK it's just a class restricted to having no non-static members, so it's analogous to those Java classes.

这篇关于在C ++中使用命名空间代替静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆