匿名命名空间:他们真的很伟大吗? [英] Anonymous namespaces: Are they really that great?

查看:153
本文介绍了匿名命名空间:他们真的很伟大吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 static 关键字来定义内部链接。后来,我改用了在匿名命名空间中包装本地东西的C ++风格。

I have been using the static keyword a long time for defining internal linkage. Later, I switched to the C++ style of wrapping local things in anonymous namespaces.

但是,现在当我使用匿名命名空间多年了,我开始认为 static 关键字很容易使用!

However, now when I have worked with anonymous namespaces for some years, I start to think that static keyword is a lot easier to work with!

一个常见的问题是我有这种模式: p>

A common problem is that I have this pattern:

namespace {
    // ...five pages of code...
}  // namespace

要查看某个函数是否具有内部或外部链接,我现在必须滚动很多,旧的C风格,我可以检查函数/对象前面是否有 static

To see if a certain function has internal or external linkage, I now have to scroll a lot, as opposed to the old C style where I could just check if the function/object had static in front of it.

知道有匿名命名空间做的事情, static 不能 - 隐藏typedefs - 但个人我不是真的很感兴趣,无论如何。

I know there are things anonymous namespaces do that static can't - hide typedefs - but personally I'm not really very interested in that, anyway.

你对此有什么看法?是匿名命名空间的伟大,它保证降低的可读性的胜利?

What are your take on this? Is the win of anonymous namespaces that great that it warrants the decreased readability? Or am I all out wrong?

推荐答案

如果你的命名空间中的代码太长,没有什么可以阻止你这样做:

If the code in your namespace is too long, there's nothing to stop you doing this:

namespace {
    int foo(char* x) {
        return x[0] + x[1];
    }
}

namespace {
    int bar(char *x, char *y) {
        return foo(x) + foo(y);
    }
}

在C ++ 03中,未命名的命名空间正是内容具有外部链接(但是在TU之外仍然是不可见的,因为没有办法引用它们)。模板参数不能具有内部链接:

In C++03 the practical advantage of using an unnamed namespace is precisely that the contents have external linkage, (but are still invisible outside the TU because there's no way to refer to them). Template parameters can't have internal linkage:

namespace {
    int foo(const char* x) {
        return x[0] + x[1];
    }
}

static int foo2(const char *x) {
    return x[0] + x[1];
}

template <int (*F)(const char*)>
void baz(const char *p) {
    F(p);
}

int main() {
    baz<foo>("ab");   // OK
    baz<foo2>("ab");  // not valid
}

这篇关于匿名命名空间:他们真的很伟大吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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